<?php

namespace App\Services\AI;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class OpenAiProvider implements LlmProvider
{
    public function respond(array $request): array
    {
        $started = (int) (microtime(true) * 1000);
        $apiKey = env('OPENAI_API_KEY');
        if (!$apiKey) {
            Log::error('openai.responses.missing_api_key');
            return [
                'text' => 'پیکربندی سرویس هوش مصنوعی ناقص است. لطفاً با پشتیبانی تماس بگیر.',
                'response_id' => null,
                'token_in' => 0,
                'token_out' => 0,
                'latency_ms' => 0,
            ];
        }
        $timeout = (int) (config('ai.timeout_seconds', 20));
        $retries = (int) (config('ai.retries', 1));

        $model = $request['model'] ?? (config('ai.modules.valuation.model') ?? 'gpt-4o-mini');
        $input = $request['input'] ?? [];

        // Extract last user message for logging
        $lastUserMessage = '';
        foreach (array_reverse($input) as $msg) {
            if (($msg['role'] ?? '') === 'user') {
                $content = $msg['content'] ?? '';
                if (is_array($content)) {
                    $content = json_encode($content, JSON_UNESCAPED_UNICODE);
                }
                if (is_string($content)) {
                    $lastUserMessage = mb_substr($content, 0, 200);
                }
                break;
            }
        }

        // Tool resources: file_search vector store ids passthrough
        $toolResources = [];
        if (!empty($request['tool_resources']['file_search']['vector_store_ids'] ?? [])) {
            $toolResources['file_search'] = [
                'vector_store_ids' => array_values($request['tool_resources']['file_search']['vector_store_ids']),
            ];
        } elseif (!empty($request['enable_file_search']) && config('ai.vector_store_id')) {
            // Auto-enable RAG for modules that support it
            $toolResources['file_search'] = [
                'vector_store_ids' => [config('ai.vector_store_id')],
            ];
        }

        // Enforce JSON schema if requested
        $responseFormat = null;
        $wantsJson = (($request['response_format']['type'] ?? null) === 'json_object');
        if ($wantsJson) {
            $responseFormat = [
                'type' => 'json_schema',
                'json_schema' => [
                    'name' => 'response',
                    'schema' => [
                        'type' => 'object',
                        'properties' => [
                            'min' => ['type' => 'number'],
                            'max' => ['type' => 'number'],
                            'anchor' => ['type' => 'number'],
                            'confidence' => ['type' => 'number'],
                            'reasons' => [
                                'type' => 'array',
                                'items' => ['type' => 'string'],
                                'minItems' => 2,
                                'maxItems' => 4,
                            ],
                        ],
                        'required' => ['min', 'max', 'anchor', 'confidence', 'reasons'],
                    ],
                ],
            ];
        }

        $payload = [
            'model' => $model,
            'input' => $input,
            'store' => (bool)($request['store'] ?? true),
        ];
        if (!empty($request['previous_response_id'])) {
            $payload['previous_response_id'] = $request['previous_response_id'];
        }
        if (!empty($toolResources)) {
            // Use 'tools' for Response API instead of 'tool_resources'
            $payload['tools'] = [
                [
                    'type' => 'file_search',
                    'vector_store_ids' => $toolResources['file_search']['vector_store_ids'],
                    'max_num_results' => 20
                ]
            ];
        }
        if ($responseFormat) {
            $payload['response_format'] = $responseFormat;
        }

        Log::info('openai.responses.request', [
            'model' => $payload['model'],
            'store' => $payload['store'],
            'message_count' => count($input),
            'has_vector_store' => !empty($toolResources),
            'vector_store_ids' => $toolResources['file_search']['vector_store_ids'] ?? null,
            'previous_response_id' => $payload['previous_response_id'] ?? null,
            'timeout' => $timeout,
            'last_user_preview' => $lastUserMessage,
        ]);

        $http = Http::timeout($timeout)->retry($retries, 1000)->withHeaders([
            'Authorization' => 'Bearer ' . $apiKey,
            'Content-Type' => 'application/json',
        ]);

        try {
            $response = $http->post('https://api.openai.com/v1/responses', $payload);
        } catch (\Illuminate\Http\Client\ConnectionException $e) {
            Log::error('openai.responses.connection_error', [
                'error' => $e->getMessage(),
                'timeout' => $timeout,
            ]);
            return [
                'text' => 'خطا در اتصال به سرویس هوش مصنوعی. لطفاً دوباره تلاش کنید.',
                'response_id' => null,
                'token_in' => 0,
                'token_out' => 0,
                'latency_ms' => (int) (microtime(true) * 1000) - $started,
            ];
        } catch (\Illuminate\Http\Client\RequestException $e) {
            Log::error('openai.responses.http_error', [
                'status' => $e->response->status(),
                'body' => $e->response->body(),
                'error' => $e->getMessage(),
                'payload' => $payload,
            ]);
            return [
                'text' => 'خطا در پردازش درخواست. لطفاً دوباره تلاش کنید.',
                'response_id' => null,
                'token_in' => 0,
                'token_out' => 0,
                'latency_ms' => (int) (microtime(true) * 1000) - $started,
            ];
        }

        $body = $response->json();
        $latency = (int) (microtime(true) * 1000) - $started;

        // Parse Response API format
        $text = 'پاسخ دریافت نشد.';
        if (!empty($body['output'])) {
            foreach ($body['output'] as $output) {
                if ($output['type'] === 'message' && !empty($output['content'])) {
                    foreach ($output['content'] as $content) {
                        if ($content['type'] === 'output_text') {
                            $text = $content['text'];
                            break 2;
                        }
                    }
                }
            }
        }

        Log::info('openai.responses.success', [
            'response_id' => $body['id'] ?? null,
            'token_in' => $body['usage']['input_tokens'] ?? 0,
            'token_out' => $body['usage']['output_tokens'] ?? 0,
            'latency_ms' => $latency,
            'text_preview' => mb_substr($text, 0, 100),
        ]);

        return [
            'text' => $text,
            'response_id' => $body['id'] ?? null,
            'token_in' => $body['usage']['input_tokens'] ?? 0,
            'token_out' => $body['usage']['output_tokens'] ?? 0,
            'latency_ms' => $latency,
        ];
    }
}
