<?php

declare(strict_types=1);

function assistant_pool_pdo(array $config): ?PDO
{
    $db = $config['database'] ?? null;
    if (! is_array($db) || empty($db['name'])) {
        return null;
    }

    try {
        $driver = strtolower((string) ($db['driver'] ?? 'mysql'));
        $host = (string) ($db['host'] ?? 'localhost');
        $name = (string) $db['name'];
        $user = (string) ($db['user'] ?? '');
        $pass = (string) ($db['pass'] ?? '');
        $port = (int) ($db['port'] ?? ($driver === 'pgsql' ? 5432 : 3306));

        if ($driver === 'pgsql') {
            $dsn = "pgsql:host={$host};port={$port};dbname={$name}";
        } else {
            $dsn = "mysql:host={$host};port={$port};dbname={$name};charset=utf8mb4";
        }

        return new PDO($dsn, $user, $pass, [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
    } catch (Throwable) {
        return null;
    }
}

function assistant_pool_now(): string
{
    // Misma zona horaria que date()/time() al escribir cooldown_until.
    // Evita desfase PHP vs MySQL NOW() (eligible en panel, 0 candidatos en el bot).
    return date('Y-m-d H:i:s');
}

function assistant_pool_reset_windows(PDO $pdo): void
{
    $minute = date('Y-m-d-H-i');
    $today = date('Y-m-d');
    $now = assistant_pool_now();

    $pdo->exec("UPDATE api_credentials SET rpm_used = 0, rpm_minute = '{$minute}' WHERE rpm_minute <> '{$minute}'");
    $pdo->exec("UPDATE api_credentials SET daily_used = 0, daily_date = '{$today}' WHERE daily_date IS NULL OR daily_date <> '{$today}'");
    $stmt = $pdo->prepare(
        'UPDATE api_credentials
         SET cooldown_until = NULL
         WHERE cooldown_until IS NOT NULL AND cooldown_until <= :now'
    );
    $stmt->execute(['now' => $now]);
}

/** @return list<array<string, mixed>> */
function assistant_pool_candidates(PDO $pdo, bool $needsTools): array
{
    assistant_pool_reset_windows($pdo);

    $toolsFilter = $needsTools ? 'AND tools_supported = 1' : '';
    $now = assistant_pool_now();

    $sql = <<<SQL
        SELECT *
        FROM api_credentials
        WHERE active = 1
          AND provider <> 'gemini'
          AND api_key <> ''
          AND api_key NOT LIKE 'PONER_%'
          AND (cooldown_until IS NULL OR cooldown_until <= :now)
          AND rpm_used < rpm_limit
          AND daily_used < daily_limit
          {$toolsFilter}
        ORDER BY priority ASC, id ASC
        SQL;

    $stmt = $pdo->prepare($sql);
    $stmt->execute(['now' => $now]);

    return $stmt->fetchAll();
}

/** @return array{eligible: int, blocked: list<array{id: int, label: string|null, provider: string, reasons: list<string>}>} */
function assistant_pool_diagnose(PDO $pdo, bool $needsTools = false): array
{
    assistant_pool_reset_windows($pdo);

    $rows = $pdo->query(
        "SELECT id, label, provider, active, api_key, cooldown_until, rpm_used, rpm_limit,
                daily_used, daily_limit, tools_supported
         FROM api_credentials
         WHERE provider <> 'gemini'
         ORDER BY priority ASC, id ASC"
    )->fetchAll();

    $eligible = 0;
    $blocked = [];

    foreach ($rows as $row) {
        $reasons = assistant_pool_block_reasons($row, $needsTools);
        if ($reasons === []) {
            $eligible++;

            continue;
        }

        $blocked[] = [
            'id' => (int) $row['id'],
            'label' => $row['label'] ?? null,
            'provider' => (string) $row['provider'],
            'reasons' => $reasons,
        ];
    }

    return ['eligible' => $eligible, 'blocked' => $blocked];
}

/** @param array<string, mixed> $row */
function assistant_pool_block_reasons(array $row, bool $needsTools): array
{
    $reasons = [];

    if ((int) ($row['active'] ?? 0) !== 1) {
        $reasons[] = 'inactive';
    }

    $apiKey = trim((string) ($row['api_key'] ?? ''));
    if ($apiKey === '' || str_starts_with($apiKey, 'PONER_')) {
        $reasons[] = 'sin_key';
    }

    $cooldown = $row['cooldown_until'] ?? null;
    if ($cooldown !== null && $cooldown !== '' && strtotime((string) $cooldown) > time()) {
        $reasons[] = 'cooldown';
    }

    if ((int) ($row['rpm_used'] ?? 0) >= (int) ($row['rpm_limit'] ?? 0)) {
        $reasons[] = 'rpm';
    }

    if ((int) ($row['daily_used'] ?? 0) >= (int) ($row['daily_limit'] ?? 0)) {
        $reasons[] = 'daily';
    }

    if ($needsTools && (int) ($row['tools_supported'] ?? 0) !== 1) {
        $reasons[] = 'no_tools';
    }

    return $reasons;
}

function assistant_pool_diagnose_summary(PDO $pdo, bool $needsTools = false): string
{
    $diagnose = assistant_pool_diagnose($pdo, $needsTools);

    if ($diagnose['eligible'] > 0) {
        return 'eligible=' . $diagnose['eligible'];
    }

    if ($diagnose['blocked'] === []) {
        return 'sin_filas_en_bd';
    }

    $parts = [];
    foreach ($diagnose['blocked'] as $row) {
        $label = trim((string) ($row['label'] ?? ''));
        $name = $label !== '' ? $label : $row['provider'];
        $parts[] = '#' . $row['id'] . ' ' . $name . ':' . implode('+', $row['reasons']);
    }

    return 'bloqueadas=' . implode('; ', array_slice($parts, 0, 6));
}

function assistant_pool_mark_used(PDO $pdo, int $id): void
{
    $minute = date('Y-m-d-H-i');
    $today = date('Y-m-d');

    $stmt = $pdo->prepare(
        'UPDATE api_credentials
         SET rpm_used = rpm_used + 1,
             daily_used = daily_used + 1,
             rpm_minute = :minute,
             daily_date = :today
         WHERE id = :id'
    );
    $stmt->execute(['minute' => $minute, 'today' => $today, 'id' => $id]);
}

function assistant_pool_cooldown(PDO $pdo, int $id, int $seconds, string $reason): void
{
    $until = date('Y-m-d H:i:s', time() + $seconds);

    $stmt = $pdo->prepare(
        'UPDATE api_credentials
         SET cooldown_until = :until,
             last_error = :reason
         WHERE id = :id'
    );
    $stmt->execute(['until' => $until, 'reason' => substr($reason, 0, 250), 'id' => $id]);
}

/**
 * Historial interno usa role=staff (respuesta humana). Las APIs OpenAI-compat
 * solo aceptan system/user/assistant/tool — sin esto Groq/Deepseek responden HTTP 400.
 *
 * @param  list<array{role: string, content: string}>  $messages
 * @return list<array{role: string, content: string}>
 */
function assistant_llm_normalize_messages(array $messages): array
{
    $normalized = [];

    foreach ($messages as $message) {
        $role = strtolower(trim((string) ($message['role'] ?? '')));
        $content = trim((string) ($message['content'] ?? ''));
        if ($content === '') {
            continue;
        }

        if ($role === 'staff') {
            $role = 'assistant';
            if (! str_starts_with($content, '[Equipo]')) {
                $content = '[Equipo] '.$content;
            }
        } elseif (! in_array($role, ['system', 'user', 'assistant', 'tool'], true)) {
            $role = 'user';
        }

        $normalized[] = ['role' => $role, 'content' => $content];
    }

    return $normalized;
}

/** @param list<array{role: string, content: string}> $messages */
function assistant_llm_request(array $credential, array $messages, array $config): array
{
    $body = [
        'model' => (string) $credential['model'],
        'messages' => assistant_llm_normalize_messages($messages),
        'max_tokens' => (int) ($config['max_tokens'] ?? 600),
        'temperature' => (float) ($config['temperature'] ?? 0.7),
    ];

    $headers = [
        'Content-Type: application/json',
        'Authorization: Bearer ' . (string) $credential['api_key'],
    ];

    if (! empty($credential['http_referer'])) {
        $headers[] = 'HTTP-Referer: ' . (string) $credential['http_referer'];
    }

    if (! empty($credential['x_title'])) {
        $headers[] = 'X-Title: ' . (string) $credential['x_title'];
    }

    $ch = curl_init((string) $credential['api_url']);
    curl_setopt_array($ch, [
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 45,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => json_encode($body, JSON_UNESCAPED_UNICODE),
    ]);

    $response = curl_exec($ch);
    $httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);

    return [
        'http' => $httpCode,
        'body' => $response === false ? '' : (string) $response,
        'curl_error' => $response === false ? curl_error($ch) : '',
    ];
}

function assistant_llm_cooldown_seconds(int $httpCode, string $body): int
{
    if ($httpCode === 429) {
        if (preg_match('/try again in (\d+(?:\.\d+)?)\s*s/i', $body, $matches)) {
            return max(60, (int) ceil((float) $matches[1]));
        }

        return 120;
    }

    if ($httpCode === 402 || strpos(strtolower($body), 'insufficient') !== false) {
        return 86400;
    }

    if ($httpCode >= 500) {
        return 120;
    }

    // 400 invalid_request (payload/role): no bloquear la key varios minutos;
    // el siguiente turno puede ir bien tras normalizar mensajes.
    $lower = strtolower($body);
    if ($httpCode === 400 && (
        str_contains($lower, 'invalid_request')
        || str_contains($lower, 'unknown variant')
        || str_contains($lower, 'discriminator')
        || str_contains($lower, "invalid value")
    )) {
        return 15;
    }

    return 300;
}

/** Modelos alternativos por proveedor cuando el principal devuelve 429. */
function assistant_llm_fallback_models(array $credential): array
{
    $provider = strtolower((string) ($credential['provider'] ?? ''));
    $model = (string) ($credential['model'] ?? '');

    if ($provider === 'groq' && str_contains($model, '70b')) {
        return ['llama-3.1-8b-instant', 'llama-3.1-70b-versatile'];
    }

    return [];
}

function assistant_llm_user_unavailable_message(array $config): string
{
    $contact = trim((string) ($config['contact_url'] ?? 'https://import.teckomp.com/#contacto'));

    return 'Disculpe, en este momento tengo alta demanda y no puedo responder. '
        . 'Intentá de nuevo en unos minutos o escribinos por la web: ' . $contact;
}

/** @param list<array{role: string, content: string}> $messages */
function assistant_llm_try_credential(PDO $pdo, array $credential, array $messages, array $config): array
{
    $label = ($credential['provider'] ?? '?') . '/' . ($credential['tier'] ?? '?');
    $models = array_values(array_unique(array_merge(
        [(string) ($credential['model'] ?? '')],
        assistant_llm_fallback_models($credential)
    )));

    $lastError = $label . ': sin respuesta';

    foreach ($models as $model) {
        if ($model === '') {
            continue;
        }

        $attempt = $credential;
        $attempt['model'] = $model;
        $result = assistant_llm_request($attempt, $messages, $config);

        if ($result['curl_error'] !== '') {
            $lastError = $label . ($model !== ($credential['model'] ?? '') ? " ($model)" : '') . ': ' . $result['curl_error'];
            assistant_pool_cooldown($pdo, (int) $credential['id'], 120, $lastError);

            return ['ok' => false, 'error' => $lastError, 'fatal' => true];
        }

        if ($result['http'] === 429 && count($models) > 1 && $model === ($credential['model'] ?? '')) {
            $lastError = $label . ' HTTP 429 en ' . $model . ' — probando modelo alternativo';
            continue;
        }

        if ($result['http'] !== 200) {
            $lastError = $label . ($model !== ($credential['model'] ?? '') ? " ($model)" : '')
                . ' HTTP ' . $result['http'] . ' ' . substr($result['body'], 0, 120);
            assistant_pool_cooldown(
                $pdo,
                (int) $credential['id'],
                assistant_llm_cooldown_seconds($result['http'], $result['body']),
                $lastError
            );

            return ['ok' => false, 'error' => $lastError, 'fatal' => false];
        }

        $decoded = json_decode($result['body'], true);
        $content = trim((string) ($decoded['choices'][0]['message']['content'] ?? ''));

        if ($content === '') {
            $lastError = $label . ($model !== ($credential['model'] ?? '') ? " ($model)" : '') . ': respuesta vacía';
            assistant_pool_cooldown($pdo, (int) $credential['id'], 60, $lastError);

            return ['ok' => false, 'error' => $lastError, 'fatal' => false];
        }

        assistant_pool_mark_used($pdo, (int) $credential['id']);
        assistant_pool_log_success($config, $credential);

        return ['ok' => true, 'content' => $content, 'error' => ''];
    }

    assistant_pool_cooldown($pdo, (int) $credential['id'], 120, $lastError);

    return ['ok' => false, 'error' => $lastError, 'fatal' => false];
}

/** @param list<array{role: string, content: string}> $history */
function assistant_call_llm_pool(array $config, array $history, string $userText, bool $needsTools = false): string
{
    $messages = [
        ['role' => 'system', 'content' => assistant_system_prompt($config)],
    ];

    foreach ($history as $item) {
        $messages[] = $item;
    }

    $messages[] = ['role' => 'user', 'content' => $userText];

    $pdo = assistant_pool_pdo($config);
    if ($pdo !== null && ! empty($config['use_credential_pool'])) {
        return assistant_call_llm_pool_db($pdo, $config, $messages, $needsTools);
    }

    return assistant_call_llm_legacy($config, $messages);
}

/** @param list<array{role: string, content: string}> $messages */
function assistant_call_llm_pool_db(PDO $pdo, array $config, array $messages, bool $needsTools): string
{
    $candidates = assistant_pool_candidates($pdo, $needsTools);
    $lastError = 'Sin credenciales disponibles (todas en cooldown o sin cupo).';

    foreach ($candidates as $credential) {
        $attempt = assistant_llm_try_credential($pdo, $credential, $messages, $config);
        if ($attempt['ok']) {
            return (string) $attempt['content'];
        }

        $lastError = (string) $attempt['error'];
        if (! empty($attempt['fatal'])) {
            continue;
        }
    }

    $legacyError = '';
    $legacy = assistant_call_llm_legacy($config, $messages, true, $legacyError);
    if ($legacy !== '') {
        return $legacy;
    }

    $logMessage = $lastError;
    if ($candidates === []) {
        $logMessage .= ' | ' . assistant_pool_diagnose_summary($pdo, $needsTools);
    }
    if ($legacyError !== '' && $legacyError !== $lastError) {
        $logMessage .= ' | legacy=' . $legacyError;
    }

    assistant_pool_log_failure($config, $logMessage);

    return assistant_llm_user_unavailable_message($config);
}

/** @param list<array{role: string, content: string}> $messages */
function assistant_call_llm_legacy(array $config, array $messages, bool $silent = false, ?string &$errorOut = null): string
{
    $providers = $config['llm_providers'] ?? [];
    $lastError = 'Sin proveedores LLM configurados.';

    foreach ($providers as $provider) {
        $apiKey = trim((string) ($provider['api_key'] ?? ''));
        if ($apiKey === '' || strpos($apiKey, 'PONER_TU_KEY') !== false || strpos($apiKey, 'PONER_') !== false) {
            continue;
        }

        $credential = [
            'model' => (string) ($provider['model'] ?? 'deepseek-chat'),
            'api_key' => $apiKey,
            'api_url' => (string) ($provider['url'] ?? ''),
            'http_referer' => $provider['http_referer'] ?? null,
            'x_title' => $provider['x_title'] ?? null,
            'provider' => $provider['name'] ?? 'legacy',
            'tier' => 'config',
        ];

        $result = assistant_llm_request($credential, $messages, $config);

        if ($result['curl_error'] !== '') {
            $lastError = $credential['provider'] . ': ' . $result['curl_error'];

            continue;
        }

        if ($result['http'] === 429 || $result['http'] >= 500) {
            $lastError = $credential['provider'] . ' HTTP ' . $result['http'];

            continue;
        }

        if ($result['http'] !== 200) {
            $lastError = $credential['provider'] . ' error: ' . substr($result['body'], 0, 200);

            continue;
        }

        $decoded = json_decode($result['body'], true);
        $content = trim((string) ($decoded['choices'][0]['message']['content'] ?? ''));

        if ($content !== '') {
            return $content;
        }

        $lastError = $credential['provider'] . ': respuesta vacía';
    }

    if ($errorOut !== null) {
        $errorOut = $lastError;
    }

    if ($silent) {
        return '';
    }

    assistant_pool_log_failure($config, $lastError);

    return assistant_llm_user_unavailable_message($config);
}

function assistant_pool_log_success(array $config, array $credential): void
{
    $label = trim((string) ($credential['label'] ?? ''));
    $name = $label !== '' ? $label : (string) ($credential['provider'] ?? '?');
    $dataDir = (string) ($config['data_dir'] ?? (dirname(__DIR__) . '/data'));
    if (! is_dir($dataDir)) {
        return;
    }

    assistant_log($dataDir . '/errors.log', 'llm_ok ' . $name);
}

function assistant_pool_log_failure(array $config, string $lastError): void
{
    $dataDir = (string) ($config['data_dir'] ?? (dirname(__DIR__) . '/data'));
    if (! is_dir($dataDir)) {
        return;
    }

    if (! function_exists('assistant_log')) {
        file_put_contents(
            $dataDir . '/errors.log',
            date('c') . ' llm_pool_failed ' . $lastError . PHP_EOL,
            FILE_APPEND | LOCK_EX
        );

        return;
    }

    assistant_log($dataDir . '/errors.log', 'llm_pool_failed ' . $lastError);
}

/** @return list<array<string, mixed>> */
function assistant_pool_status(array $config): array
{
    $pdo = assistant_pool_pdo($config);
    if ($pdo === null) {
        return [];
    }

    assistant_pool_reset_windows($pdo);

    return $pdo->query(
        'SELECT id, label, provider, tier, model, api_key, rpm_limit, rpm_used, daily_limit, daily_used,
                cooldown_until, tools_supported, priority, active, last_error
         FROM api_credentials
         ORDER BY priority ASC, id ASC'
    )->fetchAll();
}
