<?php

declare(strict_types=1);

namespace App\Services;

class OpenAiService
{
    private bool $configured;
    private string $apiKey;

    public function __construct()
    {
        $this->apiKey = $_ENV['OPEN_IA_KEY'] ?? '';
        $this->configured = !empty($this->apiKey);
    }

    public function extractBusinessCardData(string $imagePath): array
    {
        $result = [
            'first_name' => '',
            'last_name' => '',
            'email' => '',
            'phone' => '',
            'company' => '',
            'position' => '',
            'city' => '',
            'region' => '',
            'website' => '',
            'ruc' => '',
            'business_name' => '',
            'address' => '',
        ];

        if (!$this->configured) {
            return $result;
        }

        $imageContent = file_get_contents($imagePath);
        if ($imageContent === false) {
            return $result;
        }

        $base64 = base64_encode($imageContent);
        $mime = mime_content_type($imagePath) ?: 'image/jpeg';

        try {
            $payload = [
                'model' => 'gpt-4o',
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => [
                            [
                                'type' => 'text',
                                'text' => 'Extrae los datos de esta tarjeta de presentación (business card) y devuélvelos SOLO como JSON válido (sin markdown, sin explicación) con estos campos: first_name, last_name, email, phone, company, position, city, region, website, ruc, business_name, address. Usa null si un campo no se encuentra. Presta especial atención a: nombres peruanos con apellidos compuestos, RUC peruano (11 dígitos), números de celular Perú (9 dígitos empezando con 9), email, dirección fiscal, razón social.',
                            ],
                            [
                                'type' => 'image_url',
                                'image_url' => [
                                    'url' => 'data:' . $mime . ';base64,' . $base64,
                                ],
                            ],
                        ],
                    ],
                ],
                'max_tokens' => 1000,
                'temperature' => 0.1,
            ];

            $ch = curl_init('https://api.openai.com/v1/chat/completions');
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json',
                    'Authorization: Bearer ' . $this->apiKey,
                ],
                CURLOPT_POSTFIELDS => json_encode($payload),
                CURLOPT_TIMEOUT => 30,
            ]);

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

            if ($httpCode !== 200 || empty($response)) {
                error_log('OpenAI Vision error: HTTP ' . $httpCode . ' - ' . ($response ?: 'empty'));
                return $result;
            }

            $data = json_decode($response, true);
            $text = $data['choices'][0]['message']['content'] ?? '';

            // Strip markdown code fences if present
            $text = preg_replace('/^```(?:json)?\s*/i', '', $text);
            $text = preg_replace('/\s*```$/', '', $text);
            $text = trim($text);

            $parsed = json_decode($text, true);
            if (!is_array($parsed)) {
                return $result;
            }

            $result['first_name'] = $parsed['first_name'] ?? '';
            $result['last_name'] = $parsed['last_name'] ?? '';
            $result['email'] = $parsed['email'] ?? '';
            $result['phone'] = $parsed['phone'] ?? '';
            $result['company'] = $parsed['company'] ?? '';
            $result['position'] = $parsed['position'] ?? '';
            $result['city'] = $parsed['city'] ?? '';
            $result['region'] = $parsed['region'] ?? '';
            $result['website'] = $parsed['website'] ?? '';
            $result['ruc'] = $parsed['ruc'] ?? '';
            $result['business_name'] = $parsed['business_name'] ?? '';
            $result['address'] = $parsed['address'] ?? '';

            return $result;
        } catch (\Exception $e) {
            error_log('OpenAI Vision exception: ' . $e->getMessage());
            return $result;
        }
    }

    public function transcribeAudio(string $audioPath): array
    {
        $result = [
            'first_name' => '',
            'last_name' => '',
            'email' => '',
            'phone' => '',
            'company' => '',
            'position' => '',
            'city' => '',
            'region' => '',
            'raw_transcript' => '',
        ];

        if (!$this->configured) {
            return $result;
        }

        if (!file_exists($audioPath)) {
            error_log('OpenAI Whisper: audio file not found at ' . $audioPath);
            return $result;
        }

        try {
            // Step 1: Transcribe with Whisper API
            if (!file_exists($audioPath)) {
                error_log('OpenAI Whisper: file disappeared at ' . $audioPath);
                return $result;
            }

            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime = finfo_file($finfo, $audioPath) ?: 'audio/webm';
            finfo_close($finfo);

            $filename = basename($audioPath);
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
            if (empty($ext)) $ext = 'webm';

            $curlFile = new \CURLFile($audioPath, $mime, 'audio.' . $ext);

            $postData = [
                'file' => $curlFile,
                'model' => 'whisper-1',
                'language' => 'es',
                'response_format' => 'json',
            ];

            $ch = curl_init('https://api.openai.com/v1/audio/transcriptions');
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_HTTPHEADER => [
                    'Authorization: Bearer ' . $this->apiKey,
                ],
                CURLOPT_POSTFIELDS => $postData,
                CURLOPT_TIMEOUT => 60,
            ]);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($httpCode !== 200 || empty($response)) {
                error_log('OpenAI Whisper error: HTTP ' . $httpCode . ' - ' . ($response ?: 'empty'));
                return $result;
            }

            $whisperData = json_decode($response, true);
            $transcript = trim($whisperData['text'] ?? '');
            if (empty($transcript)) {
                return $result;
            }

            $result['raw_transcript'] = $transcript;

            // Step 2: Parse transcript with GPT-4o
            $payload = [
                'model' => 'gpt-4o',
                'messages' => [
                    [
                        'role' => 'user',
                        'content' => 'Se ha transcrito una conversación o dictado para registrar un lead comercial. '
                            . 'Extrae los datos de contacto y devuélvelos SOLO como JSON válido (sin markdown, sin explicación) '
                            . 'con estos campos exactos: first_name, last_name, email, phone, company, position, city, region. '
                            . 'Usa string vacío "" si un campo no se encuentra. '
                            . 'Texto transcrito: "' . $transcript . '"',
                    ],
                ],
                'max_tokens' => 500,
                'temperature' => 0.1,
            ];

            $ch = curl_init('https://api.openai.com/v1/chat/completions');
            curl_setopt_array($ch, [
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_POST => true,
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/json',
                    'Authorization: Bearer ' . $this->apiKey,
                ],
                CURLOPT_POSTFIELDS => json_encode($payload),
                CURLOPT_TIMEOUT => 30,
            ]);
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($httpCode !== 200 || empty($response)) {
                error_log('OpenAI parse error: HTTP ' . $httpCode . ' - ' . ($response ?: 'empty'));
                return $result;
            }

            $data = json_decode($response, true);
            $text = $data['choices'][0]['message']['content'] ?? '';
            $text = preg_replace('/^```(?:json)?\s*/i', '', $text);
            $text = preg_replace('/\s*```$/', '', $text);
            $text = trim($text);

            $parsed = json_decode($text, true);
            if (!is_array($parsed)) {
                return $result;
            }

            $result['first_name'] = $parsed['first_name'] ?? '';
            $result['last_name'] = $parsed['last_name'] ?? '';
            $result['email'] = $parsed['email'] ?? '';
            $result['phone'] = $parsed['phone'] ?? '';
            $result['company'] = $parsed['company'] ?? '';
            $result['position'] = $parsed['position'] ?? '';
            $result['city'] = $parsed['city'] ?? '';
            $result['region'] = $parsed['region'] ?? '';

            return $result;
        } catch (\Exception $e) {
            error_log('OpenAI Whisper exception: ' . $e->getMessage());
            return $result;
        }
    }

    public function isConfigured(): bool
    {
        return $this->configured;
    }
}
