<?php
declare(strict_types=1);

/**
 * Central multi-provider AI gateway.
 * Provider API keys are encrypted in platform_ai_providers; the encryption
 * secret is supplied by the server environment and is never stored in SQL.
 */

function eth_ai_encryption_secret(): string
{
    $value = getenv('ETHAR_AI_ENCRYPTION_SECRET');
    if (!is_string($value) || $value === '') {
        $value = (string) ($_SERVER['ETHAR_AI_ENCRYPTION_SECRET'] ?? '');
    }
    if ($value === '') {
        $value = defined('ETHAR_AI_ENCRYPTION_SECRET')
            ? (string) ETHAR_AI_ENCRYPTION_SECRET
            : '';
    }

    if (strlen($value) < 32) {
        throw new RuntimeException('AI encryption secret is not configured or is too short.');
    }

    return $value;
}

function eth_ai_encrypt_key(string $plainText): string
{
    if ($plainText === '') {
        throw new RuntimeException('API key cannot be empty.');
    }

    $nonce = random_bytes(12);
    $tag = '';
    $cipherText = openssl_encrypt(
        $plainText,
        'aes-256-gcm',
        hash('sha256', eth_ai_encryption_secret(), true),
        OPENSSL_RAW_DATA,
        $nonce,
        $tag
    );

    if (!is_string($cipherText) || $cipherText === '' || strlen($tag) !== 16) {
        throw new RuntimeException('Unable to encrypt provider API key.');
    }

    return base64_encode($nonce . $tag . $cipherText);
}

function eth_ai_key(string $cipher): string
{
    $raw = base64_decode($cipher, true);
    if ($raw === false || strlen($raw) < 29) {
        throw new RuntimeException('Invalid encrypted provider key.');
    }

    $nonce = substr($raw, 0, 12);
    $tag = substr($raw, 12, 16);
    $cipherText = substr($raw, 28);
    $plainText = openssl_decrypt(
        $cipherText,
        'aes-256-gcm',
        hash('sha256', eth_ai_encryption_secret(), true),
        OPENSSL_RAW_DATA,
        $nonce,
        $tag
    );

    if (!is_string($plainText) || $plainText === '') {
        throw new RuntimeException('Unable to decrypt provider API key.');
    }

    return $plainText;
}

function eth_ai_validate_provider(string $provider, string $model, ?string $baseUrl = null): void
{
    $provider = strtolower(trim($provider));
    $model = trim($model);
    $baseUrl = trim((string) $baseUrl);

    $allowed = ['gemini', 'openai', 'deepseek', 'openrouter', 'compatible'];
    if (!in_array($provider, $allowed, true)) {
        throw new RuntimeException('Unsupported AI provider.');
    }
    if ($model === '' || strlen($model) > 150 || preg_match('/[\x00-\x1F\x7F]/', $model)) {
        throw new RuntimeException('Invalid model identifier.');
    }

    if ($provider !== 'compatible') {
        return;
    }

    $parts = filter_var($baseUrl, FILTER_VALIDATE_URL) ? parse_url($baseUrl) : false;
    if (!is_array($parts)
        || strtolower((string) ($parts['scheme'] ?? '')) !== 'https'
        || empty($parts['host'])
        || isset($parts['user'])
        || isset($parts['pass'])
        || isset($parts['query'])
        || isset($parts['fragment'])
        || (isset($parts['port']) && (int) $parts['port'] !== 443)
    ) {
        throw new RuntimeException('المزود المتوافق يتطلب Base URL صالحًا باستخدام HTTPS والمنفذ 443 فقط، دون بيانات دخول أو Query String.');
    }

    $host = strtolower(rtrim((string) $parts['host'], '.'));
    if ($host === 'localhost'
        || str_ends_with($host, '.localhost')
        || str_ends_with($host, '.local')
        || str_ends_with($host, '.internal')
        || filter_var($host, FILTER_VALIDATE_IP)
    ) {
        throw new RuntimeException('اسم مضيف Base URL غير مسموح لأسباب أمنية. استخدم اسم نطاق عامًّا عبر HTTPS.');
    }
}

/** Resolve and pin a custom HTTPS host to a public IP to reduce SSRF/DNS-rebinding risk. */
function eth_ai_public_host_resolve(string $host): string
{
    $records = @dns_get_record($host, DNS_A | DNS_AAAA);
    if (!is_array($records) || !$records) {
        throw new RuntimeException('تعذر التحقق من عنوان خادم المزود المتوافق.');
    }

    $publicIps = [];
    foreach ($records as $record) {
        $ip = (string) ($record['ip'] ?? $record['ipv6'] ?? '');
        if ($ip === '') {
            continue;
        }
        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
            throw new RuntimeException('عنوان خادم المزود يشير إلى شبكة خاصة أو محجوزة، وقد تم رفض الاتصال.');
        }
        $publicIps[] = $ip;
    }

    if (!$publicIps) {
        throw new RuntimeException('لم يتم العثور على عنوان IP عام لخادم المزود.');
    }

    return $publicIps[0];
}

/**
 * Send a JSON POST. For custom-compatible endpoints, the DNS result is pinned
 * to a public address and redirects are disabled.
 * @return array{http_code:int,body:array<string,mixed>,curl_error:string}
 */
function eth_ai_http_post_json(string $url, array $headers, array $payload, bool $customHost = false): array
{
    if (!function_exists('curl_init')) {
        throw new RuntimeException('cURL is unavailable.');
    }

    $parts = parse_url($url);
    if (!is_array($parts) || strtolower((string) ($parts['scheme'] ?? '')) !== 'https' || empty($parts['host'])) {
        throw new RuntimeException('Invalid secure AI endpoint.');
    }

    $options = [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR),
        CURLOPT_TIMEOUT => 45,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_SSL_VERIFYHOST => 2,
        CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
        CURLOPT_REDIR_PROTOCOLS => CURLPROTO_HTTPS,
        CURLOPT_USERAGENT => 'EtharBooking-AI/1.0',
    ];

    if ($customHost) {
        $host = strtolower((string) $parts['host']);
        $ip = eth_ai_public_host_resolve($host);
        $resolved = str_contains($ip, ':') ? '[' . $ip . ']' : $ip;
        $options[CURLOPT_RESOLVE] = [$host . ':443:' . $resolved];
    }

    $handle = curl_init($url);
    if ($handle === false) {
        throw new RuntimeException('Unable to initialize secure AI connection.');
    }

    curl_setopt_array($handle, $options);
    $raw = curl_exec($handle);
    $httpCode = (int) curl_getinfo($handle, CURLINFO_HTTP_CODE);
    $curlError = curl_error($handle);
    curl_close($handle);

    $decoded = is_string($raw) ? json_decode($raw, true) : null;
    return [
        'http_code' => $httpCode,
        'body' => is_array($decoded) ? $decoded : [],
        'curl_error' => is_string($curlError) ? $curlError : '',
    ];
}

function eth_ai_request_config(array $provider, string $system, string $user): array
{
    $code = strtolower((string) ($provider['provider_code'] ?? ''));
    $model = trim((string) ($provider['model_code'] ?? ''));
    $apiKey = (string) ($provider['api_key'] ?? '');

    if ($model === '' || $apiKey === '') {
        throw new RuntimeException('AI provider configuration is incomplete.');
    }

    if ($code === 'gemini') {
        $url = 'https://generativelanguage.googleapis.com/v1beta/models/' . rawurlencode($model) . ':generateContent?key=' . rawurlencode($apiKey);
        $payload = [
            'systemInstruction' => ['parts' => [['text' => $system]]],
            'contents' => [['parts' => [['text' => $user]]]],
        ];
        return [$url, ['Content-Type: application/json'], $payload, false, 'gemini'];
    }

    if ($code === 'openai') {
        $baseUrl = 'https://api.openai.com/v1';
    } elseif ($code === 'deepseek') {
        $baseUrl = 'https://api.deepseek.com/v1';
    } elseif ($code === 'openrouter') {
        $baseUrl = 'https://openrouter.ai/api/v1';
    } elseif ($code === 'compatible') {
        $baseUrl = rtrim((string) ($provider['base_url'] ?? ''), '/');
        eth_ai_validate_provider('compatible', $model, $baseUrl);
    } else {
        throw new RuntimeException('Unsupported AI provider.');
    }

    $headers = ['Content-Type: application/json', 'Authorization: Bearer ' . $apiKey];
    if ($code === 'openrouter') {
        $headers[] = 'HTTP-Referer: https://etharbooking.com';
    }

    $payload = [
        'model' => $model,
        'messages' => [
            ['role' => 'system', 'content' => $system],
            ['role' => 'user', 'content' => $user],
        ],
        'temperature' => 0.3,
    ];

    return [$baseUrl . '/chat/completions', $headers, $payload, $code === 'compatible', 'chat'];
}

function eth_ai_extract_text(array $response, string $responseType): string
{
    $text = $responseType === 'gemini'
        ? ($response['candidates'][0]['content']['parts'][0]['text'] ?? '')
        : ($response['choices'][0]['message']['content'] ?? '');
    return is_string($text) ? trim($text) : '';
}

function eth_ai_active_provider(PDO $pdo): array
{
    $statement = $pdo->query('SELECT * FROM platform_ai_providers WHERE is_active = 1 ORDER BY priority ASC, id ASC LIMIT 1');
    $provider = $statement->fetch(PDO::FETCH_ASSOC);
    if (!$provider) {
        throw new RuntimeException('No active AI provider configured.');
    }

    $provider['api_key'] = eth_ai_key((string) $provider['api_key_ciphertext']);
    return $provider;
}

function eth_ai_call(PDO $pdo, string $system, string $user): string
{
    $provider = eth_ai_active_provider($pdo);
    [$url, $headers, $payload, $customHost, $responseType] = eth_ai_request_config($provider, $system, $user);
    $result = eth_ai_http_post_json($url, $headers, $payload, $customHost);

    if ($result['http_code'] < 200 || $result['http_code'] >= 300) {
        throw new RuntimeException('AI provider request failed (HTTP ' . $result['http_code'] . ').');
    }

    $reply = eth_ai_extract_text($result['body'], $responseType);
    if ($reply === '') {
        throw new RuntimeException('AI provider returned an empty response.');
    }

    return $reply;
}

/** Test a configured provider without changing which provider is active. */
function eth_ai_test_provider(PDO $pdo, int $providerId): array
{
    $statement = $pdo->prepare('SELECT id, provider_code, model_code, base_url, api_key_ciphertext FROM platform_ai_providers WHERE id = ? LIMIT 1');
    $statement->execute([$providerId]);
    $provider = $statement->fetch(PDO::FETCH_ASSOC);
    if (!$provider) {
        throw new RuntimeException('لم يتم العثور على المزود المطلوب.');
    }

    $provider['api_key'] = eth_ai_key((string) $provider['api_key_ciphertext']);
    [$url, $headers, $payload, $customHost, $responseType] = eth_ai_request_config(
        $provider,
        'You are a connection test. Reply only with OK.',
        'Reply only with OK.'
    );
    // Keep connection checks deliberately small to avoid unnecessary token usage.
    if ($responseType === 'gemini') {
        $payload['generationConfig'] = ['maxOutputTokens' => 16, 'temperature' => 0];
    } else {
        $payload['max_tokens'] = 16;
        $payload['temperature'] = 0;
    }

    $result = eth_ai_http_post_json($url, $headers, $payload, $customHost);
    $reply = eth_ai_extract_text($result['body'], $responseType);
    $success = $result['http_code'] >= 200 && $result['http_code'] < 300 && $reply !== '';

    if ($success) {
        return ['success' => true, 'http_code' => $result['http_code'], 'message' => 'تم الاتصال بالمزود واستلام استجابة صحيحة.'];
    }

    $code = $result['http_code'];
    if ($code === 401 || $code === 403) {
        $message = 'رفض المزود مفتاح API أو صلاحياته. راجع المفتاح والصلاحيات.';
    } elseif ($code === 429) {
        $message = 'وصل المزود إلى حد الطلبات أو الرصيد المتاح. راجع حساب المزود.';
    } elseif ($code >= 400) {
        $message = 'رفض المزود الطلب (HTTP ' . $code . '). راجع اسم النموذج وإعدادات المزود.';
    } elseif ($result['curl_error'] !== '') {
        $message = 'تعذر الاتصال بخادم المزود. تحقق من DNS وSSL واتصال الخادم بالإنترنت.';
    } else {
        $message = 'لم يقدم المزود استجابة قابلة للاستخدام. تحقق من النموذج وإعدادات الاتصال.';
    }

    return ['success' => false, 'http_code' => $code, 'message' => $message];
}
