<?php

namespace App\Services;

use App\Models\AiSetting;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class AIService
{
    protected ?AiSetting $setting = null;
    protected string $apiKey;
    protected string $apiUrl;
    protected string $model;
    protected string $provider;
    protected string $systemPrompt;
    protected int $maxTokens;
    protected float $temperature;
    protected int $maxHistory;

    public function __construct()
    {
        $this->setting = AiSetting::getActive();

        if ($this->setting) {
            $this->apiKey = $this->setting->api_key ?? '';
            $this->apiUrl = $this->setting->api_url;
            $this->model = $this->setting->model;
            $this->provider = $this->setting->provider;
            $this->systemPrompt = $this->setting->system_prompt ?? $this->getDefaultSystemPrompt();
            $this->maxTokens = $this->setting->max_tokens;
            $this->temperature = $this->setting->temperature;
            $this->maxHistory = $this->setting->max_history;
        } else {
            // Fallback to defaults if no setting is active
            $this->provider = AiSetting::PROVIDER_OPENAI;
            $this->apiKey = env('OPENAI_API_KEY', '');
            $this->apiUrl = env('OPENAI_API_URL', 'https://api.openai.com/v1');
            $this->model = env('OPENAI_MODEL', 'gpt-3.5-turbo');
            $this->systemPrompt = $this->getDefaultSystemPrompt();
            $this->maxTokens = 1000;
            $this->temperature = 0.7;
            $this->maxHistory = 10;
        }
    }

    /**
     * Get default system prompt
     */
    private function getDefaultSystemPrompt(): string
    {
        return "Sen Askeri Platform'un AI asistanısın. Askeri kariyer, sınavlar (KPSS, MSÜ, YKS), askerlik bilgileri ve mülakat hazırlığı konularında yardımcı olursun. Kısa, net ve Türkçe yanıtlar ver.";
    }

    /**
     * Generate AI response for chat completion
     */
    public function chat(array $messages, array $options = []): array
    {
        if (empty($this->apiKey) && $this->provider === AiSetting::PROVIDER_OPENAI) {
            return $this->mockResponse($messages);
        }

        // Add system prompt if not already present
        if (empty($messages) || $messages[0]['role'] !== 'system') {
            array_unshift($messages, ['role' => 'system', 'content' => $this->systemPrompt]);
        }

        try {
            $payload = $this->buildRequestPayload($messages, $options);

            $response = Http::timeout(30)->withHeaders([
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json',
            ])->post($this->apiUrl . '/chat/completions', $payload);

            if (!$response->successful()) {
                Log::error('AI API Error', [
                    'provider' => $this->provider,
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);
                return $this->mockResponse($messages);
            }

            $data = $response->json();
            return $this->parseResponse($data);

        } catch (\Exception $e) {
            Log::error('AI Service Error', [
                'provider' => $this->provider,
                'message' => $e->getMessage(),
            ]);
            return $this->mockResponse($messages);
        }
    }

    /**
     * Build request payload based on provider
     */
    private function buildRequestPayload(array $messages, array $options): array
    {
        $temperature = $options['temperature'] ?? $this->temperature;
        $maxTokens = $options['max_tokens'] ?? $this->maxTokens;
        $model = $options['model'] ?? $this->model;

        $payload = [
            'model' => $model,
            'messages' => $messages,
            'temperature' => $temperature,
            'max_tokens' => $maxTokens,
        ];

        // Provider-specific adjustments
        switch ($this->provider) {
            case AiSetting::PROVIDER_OLLAMA:
            case AiSetting::PROVIDER_LMSTUDIO:
                // Ollama and LM Studio use OpenAI-compatible API but may have slight differences
                // These typically don't support "top_p" or other advanced features
                break;

            case AiSetting::PROVIDER_OPENAI:
                // OpenAI specific options
                $payload['top_p'] = $options['top_p'] ?? 1.0;
                break;
        }

        return $payload;
    }

    /**
     * Parse response from AI provider
     */
    private function parseResponse(array $data): array
    {
        // Standard OpenAI-compatible format
        $content = $data['choices'][0]['message']['content'] ?? '';
        $usage = $data['usage'] ?? [];

        return [
            'content' => $content,
            'usage' => $usage,
            'provider' => $this->provider,
        ];
    }

    /**
     * Generate interview feedback
     */
    public function generateInterviewFeedback(array $responses, string $category): array
    {
        $systemPrompt = "Sen askeri mülakat uzmanısın. Adayın cevaplarını analiz et, puanla (0-100) ve yapıcı geri bildirim ver. Türkçe yanıt ver.";

        $userPrompt = "Kategori: {$category}\n\nCevaplar:\n";
        foreach ($responses as $question => $answer) {
            $userPrompt .= "Soru: {$question}\nCevap: {$answer}\n\n";
        }
        $userPrompt .= "\nLütfen JSON formatında yanıt ver: {\"score\": 85, \"feedback\": \"Geri bildirim\", \"strengths\": [], \"improvements\": []}";

        $messages = [
            ['role' => 'system', 'content' => $systemPrompt],
            ['role' => 'user', 'content' => $userPrompt],
        ];

        $result = $this->chat($messages, ['temperature' => 0.5, 'max_tokens' => 800]);

        // Try to parse JSON response
        $content = $result['content'];
        if (preg_match('/\{.*\}/s', $content, $matches)) {
            $json = json_decode($matches[0], true);
            if ($json) {
                return [
                    'score' => $json['score'] ?? 70,
                    'feedback' => $json['feedback'] ?? $content,
                    'strengths' => $json['strengths'] ?? [],
                    'improvements' => $json['improvements'] ?? [],
                ];
            }
        }

        return [
            'score' => 70,
            'feedback' => $content,
            'strengths' => [],
            'improvements' => [],
        ];
    }

    /**
     * Generate blog content suggestions
     */
    public function generateBlogContent(string $topic, string $category): array
    {
        $systemPrompt = "Sen askeri kariyer blog yazarısın. SEO uyumlu, bilgilendirici içerik üret. Türkçe yanıt ver.";

        $userPrompt = "Konu: {$topic}\nKategori: {$category}\n\nLütfen blog yazısı için: başlık, kısa açıklama, anahtar kelimeler ve içerik taslağı üret.";

        $messages = [
            ['role' => 'system', 'content' => $systemPrompt],
            ['role' => 'user', 'content' => $userPrompt],
        ];

        $result = $this->chat($messages, ['temperature' => 0.7, 'max_tokens' => 1000]);

        return [
            'title' => $topic,
            'excerpt' => substr($result['content'], 0, 200),
            'content' => $result['content'],
            'keywords' => $this->extractKeywords($topic),
        ];
    }

    /**
     * Generate SEO suggestions
     */
    public function generateSEOSuggestions(string $title, string $content): array
    {
        $systemPrompt = "Sen SEO uzmanısın. İçerik için meta title, meta description ve anahtar kelimeler öner. Türkçe yanıt ver.";

        $userPrompt = "Başlık: {$title}\nİçerik: " . substr($content, 0, 500) . "\n\nJSON formatında öner: {\"meta_title\": \"\", \"meta_description\": \"\", \"keywords\": []}";

        $messages = [
            ['role' => 'system', 'content' => $systemPrompt],
            ['role' => 'user', 'content' => $userPrompt],
        ];

        $result = $this->chat($messages, ['temperature' => 0.3, 'max_tokens' => 500]);

        return [
            'meta_title' => $title,
            'meta_description' => substr($result['content'], 0, 160),
            'keywords' => $this->extractKeywords($title . ' ' . $content),
        ];
    }

    /**
     * Extract keywords from text
     */
    protected function extractKeywords(string $text): array
    {
        $words = preg_split('/\s+/', strtolower(strip_tags($text)));
        $stopWords = ['ve', 'veya', 'ile', 'için', 'bu', 'şu', 'her', 'bir', 'daha', 'kadar', 'gibi'];

        $keywords = [];
        $wordCounts = array_count_values($words);

        foreach ($wordCounts as $word => $count) {
            if (strlen($word) > 3 && $count > 1 && !in_array($word, $stopWords)) {
                $keywords[] = $word;
            }
        }

        return array_slice(array_unique($keywords), 0, 10);
    }

    /**
     * Mock response when API is not configured
     */
    protected function mockResponse(array $messages): array
    {
        $lastMessage = end($messages);
        $content = $lastMessage['content'] ?? '';

        return [
            'content' => "AI servisi yapılandırılmadı. Admin panelinden AI Yönetimi bölümüne giderek ayarlarınızı yapın.\n\nMesajınız: " . substr($content, 0, 100),
            'usage' => ['prompt_tokens' => 0, 'completion_tokens' => 0, 'total_tokens' => 0],
            'provider' => $this->provider,
        ];
    }

    /**
     * Check if AI service is configured
     */
    public function isConfigured(): bool
    {
        if (!$this->setting) {
            return false;
        }

        // OpenAI requires API key
        if ($this->setting->provider === AiSetting::PROVIDER_OPENAI) {
            return !empty($this->apiKey);
        }

        // Other providers typically don't require API key (local)
        return true;
    }

    /**
     * Get current provider
     */
    public function getProvider(): string
    {
        return $this->provider;
    }

    /**
     * Get current model
     */
    public function getModel(): string
    {
        return $this->model;
    }

    /**
     * Test connection to AI provider
     */
    public static function testConnection(AiSetting $setting): array
    {
        try {
            $service = new self();
            $service->setting = $setting;
            $service->apiKey = $setting->api_key ?? '';
            $service->apiUrl = $setting->api_url;
            $service->model = $setting->model;
            $service->provider = $setting->provider;

            $testPayload = [
                'model' => $setting->model,
                'messages' => [
                    ['role' => 'user', 'content' => 'Merhaba'],
                ],
                'temperature' => 0.5,
                'max_tokens' => 50,
            ];

            $response = Http::timeout(10)->withHeaders([
                'Authorization' => 'Bearer ' . $setting->api_key,
                'Content-Type' => 'application/json',
            ])->post($setting->api_url . '/chat/completions', $testPayload);

            if ($response->successful()) {
                return [
                    'success' => true,
                    'message' => 'Bağlantı başarılı! API yanıt veriyor.',
                ];
            }

            return [
                'success' => false,
                'message' => 'Bağlantı başarısız. HTTP ' . $response->status() . ': ' . $response->body(),
            ];

        } catch (\Exception $e) {
            return [
                'success' => false,
                'message' => 'Hata: ' . $e->getMessage(),
            ];
        }
    }
}
