<?php
namespace EasyChat\Library\AiProvider;

use EasyChat\Library\EasyTokensClientHeaders;
use EasyChat\Library\Http\ExternalHttpClient;







class OpenAiCompatibleTransport {
    private $proxy;
    private $trustedResolve;
    private $lastCurlError = '';
    private $lastHttpStatus = 0;

    public function __construct(array $proxy = [], array $trustedResolve = []) {
        $this->proxy = array_merge([
            'ip' => null,
            'port' => null,
            'login' => null,
            'password' => null,
        ], $proxy);
        $this->trustedResolve = $this->normalizeTrustedResolve($trustedResolve);
    }

    public function buildOptions($url, $body, array $headers, array $extraOptions = []) {
        if (self::isEasyTokensUrl($url)) {
            $headers = EasyTokensClientHeaders::append($headers);
        }
        $options = [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_CONNECTTIMEOUT => 10,
            CURLOPT_TIMEOUT => 35,
            CURLOPT_NOSIGNAL => 1,
            CURLOPT_SSL_VERIFYHOST => 2,
            CURLOPT_SSL_VERIFYPEER => true,
        ];
        if (self::isEasyTokensUrl($url) && $this->trustedResolve) {
             
             
            $options[CURLOPT_RESOLVE] = $this->trustedResolve;
        }
        if (!empty($this->proxy['ip']) && !empty($this->proxy['port'])) {
            $proxyIp = strpos($this->proxy['ip'], ':') !== false
                ? '[' . $this->proxy['ip'] . ']'
                : $this->proxy['ip'];
            $options[CURLOPT_PROXY] = $proxyIp;
            $options[CURLOPT_PROXYPORT] = $this->proxy['port'];
            if (!empty($this->proxy['login']) && !empty($this->proxy['password'])) {
                $options[CURLOPT_PROXYUSERPWD] = $this->proxy['login'] . ':' . $this->proxy['password'];
            }
        }
        foreach ($extraOptions as $key => $value) {
            $options[$key] = $value;
        }
        return $options;
    }

    private function normalizeTrustedResolve(array $entries): array {
        $normalized = [];
        foreach (array_slice($entries, 0, 1) as $entry) {
            $entry = trim((string)$entry);
            if (strlen($entry) > 192 || preg_match(
                '/^api\.easytokens\.ru:443:(?:[0-9]{1,3}\.){3}[0-9]{1,3}(?:,(?:[0-9]{1,3}\.){3}[0-9]{1,3}){0,2}$/D',
                $entry
            ) !== 1) {
                continue;
            }
            $normalized[] = $entry;
        }
        return $normalized;
    }

    public function execute(array $options) {
        $response = (new ExternalHttpClient())->requestCurlOptions($options, 'ai', false);
        $this->lastCurlError = (string)($response['curl_error'] ?? '');
        $this->lastHttpStatus = (int)($response['http_code'] ?? 0);
        return $response['raw'] ?? false;
    }

    public function getLastCurlError() {
        return $this->lastCurlError;
    }

    public function getLastHttpStatus() {
        return $this->lastHttpStatus;
    }

    public static function isEasyTokensUrl($url) {
        $host = parse_url((string)$url, PHP_URL_HOST);
        if (!is_string($host) || $host === '') {
            return false;
        }
        $host = strtolower($host);
        return $host === 'api.easytokens.ru'
            || $host === 'easytokens.ru'
            || substr($host, -14) === '.easytokens.ru';
    }
}
