<?php

namespace App\Services;

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

class AiRewriter
{
    private static array $prompts = [
        'Sports'        => "You are a seasoned human sports journalist at a major news outlet. Write with energy and authority — like someone who has covered football, athletics, and sport their whole career.",
        'Entertainment' => "You are a veteran human entertainment reporter at a popular media company. Write with personality and cultural awareness — like someone deeply embedded in the entertainment industry.",
        'Technology'    => "You are a sharp human tech journalist at a leading digital publication. Write with clarity and insight — translate complex tech into compelling stories for general readers.",
        'Politics'      => "You are an experienced human political correspondent at a respected news organisation. Write with authority and balance — present facts fairly without bias.",
        'Breaking News' => "You are a seasoned human breaking news reporter at a major wire service. Write with urgency and precision — most important facts first, every word earns its place.",
    ];

    /**
     * Rewrite an article using the configured AI provider.
     * Returns ['title' => string, 'content' => string] or null on failure/disabled.
     */
    public static function rewrite(string $title, string $content, string $category = 'Breaking News'): ?array
    {
        $provider = strtolower(env('AI_PROVIDER', 'none'));
        if ($provider === 'none') return null;

        $style        = self::$prompts[$category] ?? self::$prompts['Breaking News'];
        $systemPrompt = $style . "\n\n"
            . "Rewrite the article below following these rules:\n"
            . "1. HUMAN TONE: Write exactly as a human journalist would. Vary sentence length. Use active voice. Never use AI giveaways like \"It is worth noting\", \"In conclusion\", \"Delve into\", \"It's important to\", \"As an AI\".\n"
            . "2. SEO TITLE: Write a compelling, keyword-rich headline under 70 characters. Put the main subject or action first.\n"
            . "3. SEO CONTENT: Naturally include the key subject in the first sentence. Use one descriptive <h2> subheading mid-article. Bold key names or stats with <strong> where it aids scanning.\n"
            . "4. ACCURACY: Preserve ALL facts, names, quotes, dates, and figures exactly — do not invent anything.\n"
            . "5. LENGTH: 6-10 paragraphs depending on source material. Tight, punchy paragraphs.\n"
            . "6. OUTPUT FORMAT: Return ONLY a raw JSON object with exactly two keys:\n"
            . "   \"title\" — the rewritten headline (plain text, no HTML tags)\n"
            . "   \"content\" — the article body (valid HTML using only <p>, <h2>, <strong>, <em>)\n"
            . "   No markdown, no code fences, no explanation — just the JSON.";

        $userPrompt = "Original title: {$title}\n\nOriginal content:\n" . mb_substr(strip_tags($content), 0, 3000);

        try {
            $raw = match ($provider) {
                'openai' => self::openai($systemPrompt, $userPrompt),
                'gemini' => self::gemini($systemPrompt, $userPrompt),
                'ollama' => self::ollama($systemPrompt, $userPrompt),
                default  => null,
            };

            return $raw ? self::parseJson($raw) : null;
        } catch (\Exception $e) {
            Log::warning("AiRewriter [{$provider}] failed: " . $e->getMessage());
            return null;
        }
    }

    // ── Parse AI JSON response ───────────────────────────────────────────────
    private static function parseJson(string $raw): ?array
    {
        // Strip any accidental markdown code fences
        $raw = preg_replace('/^```(?:json)?\s*/i', '', trim($raw));
        $raw = preg_replace('/\s*```$/', '', $raw);

        $data = json_decode(trim($raw), true);

        if (
            is_array($data)
            && !empty($data['title'])
            && !empty($data['content'])
        ) {
            return [
                'title'   => trim(strip_tags($data['title'])),
                'content' => trim($data['content']),
            ];
        }

        Log::warning('AiRewriter: could not parse JSON response — ' . mb_substr($raw, 0, 200));
        return null;
    }

    // ── OpenAI ──────────────────────────────────────────────────────────────
    private static function openai(string $system, string $user): ?string
    {
        $key   = env('OPENAI_API_KEY');
        $model = env('OPENAI_MODEL', 'gpt-4o-mini');
        if (!$key) return null;

        $res = Http::withToken($key)
            ->timeout(30)
            ->post('https://api.openai.com/v1/chat/completions', [
                'model'           => $model,
                'max_tokens'      => 1200,
                'temperature'     => 0.7,
                'response_format' => ['type' => 'json_object'],
                'messages'        => [
                    ['role' => 'system', 'content' => $system],
                    ['role' => 'user',   'content' => $user],
                ],
            ]);

        if (!$res->successful()) {
            Log::warning('OpenAI error: ' . $res->body());
            return null;
        }

        return $res->json('choices.0.message.content');
    }

    // ── Google Gemini ───────────────────────────────────────────────────────
    private static function gemini(string $system, string $user): ?string
    {
        $key   = env('GEMINI_API_KEY');
        $model = env('GEMINI_MODEL', 'gemini-1.5-flash');
        if (!$key) return null;

        $res = Http::timeout(30)
            ->post("https://generativelanguage.googleapis.com/v1beta/models/{$model}:generateContent?key={$key}", [
                'contents' => [[
                    'parts' => [['text' => $system . "\n\n" . $user]],
                ]],
                'generationConfig' => [
                    'maxOutputTokens' => 1200,
                    'temperature'     => 0.7,
                    'responseMimeType' => 'application/json',
                ],
            ]);

        if (!$res->successful()) {
            Log::warning('Gemini error: ' . $res->body());
            return null;
        }

        return $res->json('candidates.0.content.parts.0.text');
    }

    // ── Ollama (local) ──────────────────────────────────────────────────────
    private static function ollama(string $system, string $user): ?string
    {
        $url   = rtrim(env('OLLAMA_URL', 'http://localhost:11434'), '/');
        $model = env('OLLAMA_MODEL', 'llama3.2');

        $res = Http::timeout(120)->post("{$url}/api/generate", [
            'model'   => $model,
            'prompt'  => $system . "\n\n" . $user,
            'stream'  => false,
            'format'  => 'json',
            'options' => ['temperature' => 0.7, 'num_predict' => 1200],
        ]);

        if (!$res->successful()) return null;

        return $res->json('response');
    }
}
