<?php

namespace App\Services;

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

class AIKeywordExtractor
{
    private string $provider;
    private string $apiKey;
    private string $model;
    private float $temperature;
    private int $maxTokens;
    private int $rateLimitMs;

    public function __construct()
    {
        $this->provider = config('services.ai.provider', 'openai');
        $this->apiKey = config('services.openai.api_key');
        $this->model = config('services.openai.model', 'gpt-4o-mini');
        $this->temperature = (float) config('services.openai.temperature', 0.3);
        $this->maxTokens = (int) config('services.openai.max_tokens', 500);
        $this->rateLimitMs = config('services.openai.rate_limit_ms', 50);
    }

    /**
     * Extract keywords from page content
     */
    public function extractKeywords(string $content, string $pageType = 'product', array $metadata = []): array
    {
        // Rate limiting
        usleep($this->rateLimitMs * 1000);

        $systemPrompt = $this->buildSystemPrompt($pageType);
        $userPrompt = $this->buildUserPrompt($content, $metadata);

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

            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $this->apiKey,
                'Content-Type' => 'application/json',
            ])
            ->timeout(60)
            ->post('https://api.openai.com/v1/chat/completions', [
                'model' => $this->model,
                'messages' => $messages,
                'temperature' => $this->temperature,
                'max_tokens' => $this->maxTokens,
                'response_format' => ['type' => 'json_object'],
            ]);

            if (!$response->successful()) {
                throw new \Exception('OpenAI API error: ' . $response->body());
            }

            $data = $response->json();
            $resultText = $data['choices'][0]['message']['content'] ?? '{}';
            $result = json_decode($resultText, true);

            // Log API usage
            $tokens = $data['usage']['total_tokens'] ?? 0;
            $cost = $this->calculateCost($data['usage'] ?? []);
            ApiUsageLog::logUsage('openai', $cost, null, ['tokens' => $tokens]);

            return $result['keywords'] ?? [];

        } catch (\Exception $e) {
            Log::error('AI keyword extraction failed', [
                'error' => $e->getMessage(),
                'page_type' => $pageType,
            ]);

            return [];
        }
    }

    /**
     * Build system prompt based on page type
     */
    private function buildSystemPrompt(string $pageType): string
    {
        return <<<PROMPT
You are an expert SEO analyst. Analyze the provided webpage content and extract 15-20 keyword candidates.

For each keyword, provide:
1. keyword: The actual keyword phrase (2-4 words preferred)
2. relevance_score: 0-100 score based on relevance to the content
3. search_intent: One of [informational, commercial, transactional, navigational]
4. reasoning: Brief explanation (1 sentence)

Focus on:
- Keywords that naturally appear in the content
- Commercial/transactional intent keywords for product pages
- Informational intent keywords for blog posts
- Long-tail variations with lower competition potential
- Semantic variations and related terms

Return ONLY valid JSON in this format:
{
  "keywords": [
    {
      "keyword": "example keyword",
      "relevance_score": 85,
      "search_intent": "commercial",
      "reasoning": "This keyword appears multiple times and matches the product description."
    }
  ]
}
PROMPT;
    }

    /**
     * Build user prompt with content and metadata
     */
    private function buildUserPrompt(string $content, array $metadata): string
    {
        $prompt = "Page Type: " . ($metadata['page_type'] ?? 'unknown') . "\n\n";

        if (!empty($metadata['title'])) {
            $prompt .= "Title: " . $metadata['title'] . "\n";
        }

        if (!empty($metadata['meta_description'])) {
            $prompt .= "Meta Description: " . $metadata['meta_description'] . "\n";
        }

        if (!empty($metadata['h1'])) {
            $prompt .= "H1: " . $metadata['h1'] . "\n";
        }

        $prompt .= "\nContent:\n" . $content;

        return $prompt;
    }

    /**
     * Calculate API cost based on token usage
     */
    private function calculateCost(array $usage): float
    {
        $inputTokens = $usage['prompt_tokens'] ?? 0;
        $outputTokens = $usage['completion_tokens'] ?? 0;

        // Prices per 1M tokens for gpt-4o-mini
        $inputCostPerM = 0.15;
        $outputCostPerM = 0.60;

        $inputCost = ($inputTokens / 1000000) * $inputCostPerM;
        $outputCost = ($outputTokens / 1000000) * $outputCostPerM;

        return $inputCost + $outputCost;
    }
}
