<?php
declare(strict_types=1);

/**
 * NEXAMISI AI ENGINE - VERSION 2
 * PHP 8.2+
 *
 * File:
 * nexamisi/app/AIEngine.php
 *
 * Fitur:
 * - OpenAI Responses API
 * - Web Search khusus Market Research AI-02
 * - Task execution
 * - Output validation
 * - Token usage logging
 * - Error diagnostics
 */

final class NEXAMISI_AIEngine
{
    private PDO $pdo;
    private array $config;

    public function __construct(PDO $pdo, array $config)
    {
        $this->pdo = $pdo;
        $this->config = $config;
    }

    public function runTask(int $taskId): array
    {
        if ($taskId < 1) {
            throw new InvalidArgumentException(
                'ID tugas tidak valid.'
            );
        }

        /*
         * 1. API CONFIGURATION
         */

        $key = (string) (
            $this->config['openai_api_key'] ?? ''
        );

        $key = preg_replace(
            '/[\x{200E}\x{200F}\x{FEFF}]/u',
            '',
            trim($key)
        );

        if ($key === null) {
            throw new RuntimeException(
                'Gagal membersihkan API key.'
            );
        }

        $model = trim(
            (string) ($this->config['openai_model'] ?? '')
        );

        if ($key === '' || $model === '') {
            throw new RuntimeException(
                'API key atau model OpenAI belum dikonfigurasi.'
            );
        }

        if (!function_exists('curl_init')) {
            throw new RuntimeException(
                'Ekstensi PHP cURL belum aktif.'
            );
        }

        /*
         * 2. LOAD TASK AND EMPLOYEE
         */

        $stmt = $this->pdo->prepare(
            'SELECT
                t.id,
                t.title,
                t.description,
                t.employee_id,
                e.code AS employee_code,
                e.name AS employee_name,
                e.role AS employee_role,
                e.instruction AS employee_instruction,
                e.status AS employee_status
             FROM tasks t
             INNER JOIN employees e
                ON e.id = t.employee_id
             WHERE t.id = :id
             LIMIT 1'
        );

        $stmt->execute([
            ':id' => $taskId
        ]);

        $task = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$task) {
            throw new RuntimeException(
                'Tugas atau karyawan AI tidak ditemukan.'
            );
        }

        if (
            (string) $task['employee_status']
            !== 'active'
        ) {
            throw new RuntimeException(
                'Karyawan AI tidak aktif.'
            );
        }

        /*
         * 3. EMPLOYEE INSTRUCTIONS
         */

        $instructions = trim(
            (string) (
                $task['employee_instruction'] ?? ''
            )
        );

        if ($instructions === '') {
            $instructions =
                'Kamu adalah karyawan AI NEXAMISI. '
                . 'Kerjakan tugas secara akurat, jujur, '
                . 'dan profesional. Jangan mengarang data, '
                . 'harga, sumber, statistik, atau hasil.';
        }

        /*
         * 4. BUILD TASK INPUT
         */

        $input =
            "INSTRUKSI KHUSUS KARYAWAN:\n"
            . $instructions

            . "\n\nDATA TUGAS:\n"

            . "Nama karyawan: "
            . (string) $task['employee_name']

            . "\nKode karyawan: "
            . (string) $task['employee_code']

            . "\nPeran: "
            . (string) $task['employee_role']

            . "\nJudul tugas: "
            . (string) $task['title']

            . "\nDeskripsi:\n"
            . (
                trim(
                    (string) ($task['description'] ?? '')
                ) ?: '(Tidak ada deskripsi)'
            )

            . "\n\nKerjakan tugas dengan lengkap. "
            . "Berikan hasil yang dapat ditinjau CEO. "
            . "Jangan melakukan tindakan eksternal seperti "
            . "memposting, membeli, atau mengirim pesan.";

        /*
         * 5. DETECT MARKET RESEARCH EMPLOYEE
         */

        $employeeCode = strtoupper(
            trim((string) $task['employee_code'])
        );

        $employeeRole = (string) $task['employee_role'];

        $isMarketResearch =
            $employeeCode === 'AI-02'
            || stripos(
                $employeeRole,
                'Market Research'
            ) !== false;

        /*
         * 6. BASE PAYLOAD
         */

        $payload = [
            'model' => $model,
            'input' => $input,
            'max_output_tokens' => 6000
        ];

        /*
         * 7. MARKET RESEARCH WEB SEARCH
         */

        if ($isMarketResearch) {

            $payload['tools'] = [
                [
                    'type' => 'web_search',
                    'search_context_size' => 'medium'
                ]
            ];

            $payload['tool_choice'] = 'required';

            $payload['max_tool_calls'] = 5;

            $payload['input'] .=

                "\n\n"
                . "ATURAN WAJIB MARKET RESEARCH:\n"

                . "1. Lakukan pencarian web aktual sebelum "
                . "menyusun kesimpulan.\n"

                . "2. Periksa minimal 3 sumber relevan "
                . "jika sumber tersedia.\n"

                . "3. Utamakan situs resmi brand, "
                . "marketplace, dan program affiliate.\n"

                . "4. Cari 5 kandidat produk affiliate "
                . "yang relevan untuk pasar Indonesia.\n"

                . "5. Periksa harga, ketersediaan, "
                . "dan komisi apabila datanya tersedia.\n"

                . "6. Cantumkan tautan sumber yang benar-benar "
                . "ditemukan melalui pencarian web.\n"

                . "7. Cantumkan tanggal pemeriksaan.\n"

                . "8. Bedakan fakta, perkiraan, "
                . "dan informasi yang belum terverifikasi.\n"

                . "9. Jangan mengarang harga, komisi, "
                . "jumlah penjualan, rating, atau tren.\n"

                . "10. Jika informasi tidak ditemukan, "
                . "tulis Belum Terverifikasi.\n"

                . "11. Untuk setiap kandidat, jelaskan "
                . "target konsumen dan masalah yang diselesaikan.\n"

                . "12. Berikan alasan mengapa produk "
                . "layak diuji sebagai affiliate.\n"

                . "13. Berikan tabel perbandingan "
                . "5 kandidat produk.\n"

                . "14. Akhiri dengan rekomendasi "
                . "3 produk untuk diuji CEO.\n"

                . "15. Jangan menyatakan suatu produk "
                . "memiliki komisi affiliate aktif "
                . "tanpa bukti sumber.\n"

                . "16. Jangan menganggap hasil pencarian "
                . "sebagai bukti jumlah penjualan.\n"

                . "17. Buat laporan terstruktur, "
                . "jelas, dan lengkap.";
        }

        /*
         * 8. ENCODE JSON
         */

        $json = json_encode(
            $payload,
            JSON_UNESCAPED_UNICODE
            | JSON_UNESCAPED_SLASHES
        );

        if ($json === false) {
            throw new RuntimeException(
                'Gagal membuat JSON: '
                . json_last_error_msg()
            );
        }

        /*
         * 9. SEND REQUEST
         */

        $requestId = '';

        $ch = curl_init(
            'https://api.openai.com/v1/responses'
        );

        curl_setopt_array($ch, [

            CURLOPT_POST => true,

            CURLOPT_RETURNTRANSFER => true,

            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $key
            ],

            CURLOPT_POSTFIELDS => $json,

            CURLOPT_CONNECTTIMEOUT => 20,

            CURLOPT_TIMEOUT => 180,

            CURLOPT_HEADERFUNCTION =>
                static function (
                    $curl,
                    string $header
                ) use (&$requestId): int {

                    if (
                        stripos(
                            $header,
                            'x-request-id:'
                        ) === 0
                    ) {
                        $requestId = trim(
                            substr(
                                $header,
                                strlen('x-request-id:')
                            )
                        );
                    }

                    return strlen($header);
                }
        ]);

        $raw = curl_exec($ch);

        $http = (int) curl_getinfo(
            $ch,
            CURLINFO_HTTP_CODE
        );

        $curlError = curl_error($ch);

        curl_close($ch);

        if ($raw === false) {
            throw new RuntimeException(
                'Koneksi OpenAI gagal: '
                . $curlError
            );
        }

        /*
         * 10. DECODE RESPONSE
         */

        $data = json_decode($raw, true);

        if (!is_array($data)) {
            throw new RuntimeException(
                'Respons OpenAI bukan JSON valid. '
                . 'HTTP: ' . $http
                . ' | Respons: '
                . substr((string) $raw, 0, 1000)
            );
        }

        /*
         * 11. HANDLE API ERRORS
         */

        if ($http < 200 || $http >= 300) {

            $apiError = is_array(
                $data['error'] ?? null
            ) ? $data['error'] : [];

            $diagnostic = [
                'http_status' => $http,

                'message' =>
                    $apiError['message']
                    ?? 'OpenAI menolak permintaan.',

                'error_type' =>
                    $apiError['type'] ?? null,

                'error_code' =>
                    $apiError['code'] ?? null,

                'error_param' =>
                    $apiError['param'] ?? null,

                'request_id' =>
                    $requestId !== ''
                    ? $requestId
                    : null
            ];

            throw new RuntimeException(
                'DETAIL OPENAI: '
                . json_encode(
                    $diagnostic,
                    JSON_UNESCAPED_UNICODE
                    | JSON_UNESCAPED_SLASHES
                )
            );
        }

        /*
         * 12. CHECK RESPONSE STATUS
         */

        $responseStatus = (string) (
            $data['status'] ?? 'unknown'
        );

        if ($responseStatus === 'incomplete') {

            $incomplete = (
                $data['incomplete_details'] ?? []
            );

            $reason = is_array($incomplete)
                ? ($incomplete['reason'] ?? 'unknown')
                : 'unknown';

            throw new RuntimeException(
                'AI belum menyelesaikan tugas. '
                . 'Status: incomplete'
                . ' | Alasan: ' . $reason
                . ' | Coba jalankan kembali.'
            );
        }

        if ($responseStatus !== 'completed') {
            throw new RuntimeException(
                'Status respons OpenAI tidak selesai: '
                . $responseStatus
            );
        }

        /*
         * 13. EXTRACT OUTPUT TEXT
         */

        $answer = trim(
            (string) ($data['output_text'] ?? '')
        );

        if (
            $answer === ''
            && isset($data['output'])
            && is_array($data['output'])
        ) {

            $textParts = [];

            foreach ($data['output'] as $item) {

                if (!is_array($item)) {
                    continue;
                }

                foreach (
                    ($item['content'] ?? [])
                    as $content
                ) {

                    if (!is_array($content)) {
                        continue;
                    }

                    if (
                        ($content['type'] ?? '')
                        === 'output_text'
                        && isset($content['text'])
                    ) {
                        $textParts[] =
                            (string) $content['text'];
                    }
                }
            }

            $answer = trim(
                implode("\n", $textParts)
            );
        }

        if ($answer === '') {
            throw new RuntimeException(
                'OpenAI menyelesaikan respons '
                . 'tetapi teks hasil tidak ditemukan.'
            );
        }

        /*
         * 14. SAVE TASK RESULT
         */

        $save = $this->pdo->prepare(
            'UPDATE tasks
             SET result = :result
             WHERE id = :id'
        );

        $save->execute([
            ':result' => $answer,
            ':id' => $taskId
        ]);

        /*
         * 15. SAVE TOKEN USAGE
         */

        $usage = is_array(
            $data['usage'] ?? null
        ) ? $data['usage'] : [];

        try {

            $log = $this->pdo->prepare(
                'INSERT INTO ai_usage_logs
                (
                    task_id,
                    employee_code,
                    model,
                    input_tokens,
                    output_tokens,
                    total_tokens,
                    response_id
                )
                VALUES
                (
                    :task_id,
                    :employee_code,
                    :model,
                    :input_tokens,
                    :output_tokens,
                    :total_tokens,
                    :response_id
                )'
            );

            $log->execute([

                ':task_id' => $taskId,

                ':employee_code' =>
                    $employeeCode,

                ':model' => $model,

                ':input_tokens' =>
                    (int) (
                        $usage['input_tokens'] ?? 0
                    ),

                ':output_tokens' =>
                    (int) (
                        $usage['output_tokens'] ?? 0
                    ),

                ':total_tokens' =>
                    (int) (
                        $usage['total_tokens'] ?? 0
                    ),

                ':response_id' =>
                    (string) (
                        $data['id'] ?? ''
                    )
            ]);

        } catch (Throwable $e) {

            error_log(
                'NEXAMISI AI usage log: '
                . $e->getMessage()
            );
        }

        /*
         * 16. RETURN RESULT
         */

        return [

            'ok' => true,

            'result' => $answer,

            'usage' => $usage,

            'response_id' =>
                (string) ($data['id'] ?? ''),

            'employee_code' => $employeeCode,

            'web_search_enabled' =>
                $isMarketResearch
        ];
    }
}
