<?php

namespace Kanews\Kai\AI;

use Kanews\Kai\Support\Options;

class PromptFactory
{
    public static function build(string $task, array $context): array
    {
        $method = 'build' . str_replace(' ', '', ucwords(str_replace(['-', '_'], ' ', $task)));
        if (method_exists(__CLASS__, $method)) {
            return self::$method($context);
        }

        return self::buildSummary($context);
    }

    private static function basePrompt(string $task, array $context, string $defaultModel = 'gpt-4o-mini'): array
    {
        return [
            'task'     => $task,
            'model'    => $context['model'] ?? $defaultModel,
            'messages' => [],
        ];
    }

    private static function buildExcerpt(array $context): array
    {
        $prompt = self::basePrompt('excerpt', $context);
        $prompt['messages'] = [
            [
                'role'    => 'system',
                'content' => "You are a professional news editor. Create a compelling news excerpt by following these steps:\n\n1. First, analyze the content and detect its language\n2. Then, create a journalistic lead paragraph that:\n   - Captures the most newsworthy aspects\n   - Answers the key questions (Who, What, Where, When, Why)\n   - Is between 100-150 characters\n   - Uses the same language as the content\n   - Follows news writing best practices\n\nRules:\n- Write in clear, concise journalistic style\n- Focus on facts and key information\n- Use active voice and strong verbs\n- Maintain the original language of the content\n- Avoid sensationalism while keeping reader interest\n- Include the most relevant keywords naturally\n- Return only the excerpt text without formatting",
            ],
            [
                'role'    => 'user',
                'content' => (string) ($context['text'] ?? ''),
            ],
        ];
        return $prompt;
    }

    private static function buildSummary(array $context): array
    {
        $prompt = self::basePrompt('summary', $context);
        $prompt['messages'] = [
            [
                'role'    => 'system',
                'content' => "You are a professional news summarizer. Follow these steps strictly:\n\n1. IMPORTANT - LANGUAGE RULE:\n   - Detect the language of the provided content\n   - Write the summary in EXACTLY THE SAME LANGUAGE as the source content\n\n2. Create a three-paragraph news summary that covers introduction, development, and conclusion sections in the same language.\n\nRules:\n- Keep the EXACT SAME LANGUAGE as the source content\n- Write in professional journalistic style\n- Use clear, factual language\n- Include relevant statistics and quotes when available\n- Follow inverted pyramid structure\n- Focus on accuracy and objectivity\n- Avoid editorializing or speculation\n- Keep paragraphs concise and well-structured",
            ],
            [
                'role'    => 'user',
                'content' => (string) ($context['text'] ?? ''),
            ],
        ];
        return $prompt;
    }

    private static function buildSeoTitle(array $context): array
    {
        $prompt = self::basePrompt('seo-title', $context);
        $prompt['messages'] = [
            [
                'role'    => 'system',
                'content' => "You are a professional news headline generator for a news website. Follow these steps:\n1. Detect the language of the content\n2. Identify key newsworthy elements (who, what, where, when, why)\n3. Create a news headline in the SAME LANGUAGE that:\n   - Leads with the most important information\n   - Is under 70 characters\n   - Uses active voice and strong verbs\n   - Includes relevant keywords for SEO\n   - Maintains journalistic integrity\nRules:\n- Write in the exact same language as the content\n- Focus on facts, not speculation\n- Avoid clickbait tactics while maintaining interest\n- Return only the headline text",
            ],
            [
                'role'    => 'user',
                'content' => (string) ($context['text'] ?? ''),
            ],
        ];

        return $prompt;
    }

    private static function buildChatMessage(array $context): array
    {
        $prompt = self::basePrompt('chat-message', $context, 'gpt-3.5-turbo');
        $title   = $context['article_title'] ?? '';
        $snippet = $context['snippet'] ?? '';
        $user    = $context['user_message'] ?? '';

        $prompt['messages'] = [
            [
                'role'    => 'system',
                'content' => 'Sen bir haber makalesi hakkında sohbet eden yardımcı bir asistansın. ' .
                    'Makale başlığı: ' . $title . "\n" .
                    'Makale içeriği özeti: ' . $snippet . "...\n" .
                    'Makale hakkında sorulan sorulara kısa ve öz yanıtlar ver.',
            ],
            [
                'role'    => 'user',
                'content' => (string) $user,
            ],
        ];

        $prompt['max_tokens'] = 150;
        return $prompt;
    }

    private static function buildComments(array $context): array
    {
        $count = (int) ($context['count'] ?? 5);
        $title = $context['title'] ?? '';
        $prompt = self::basePrompt('comments', $context);

        $prompt['messages'] = [
            [
                'role'    => 'system',
                'content' => sprintf(
                    "Generate %d realistic comments for a blog post. Detect the language of the content and create comments in the SAME language. Each comment should include:\n1. A realistic name (mix of full names and nicknames)\n2. A valid email format\n3. Comment text that is 1-3 sentences long and relates directly to the content\nMake comments diverse in opinion, some positive, some neutral, some questioning.\nFormat as JSON array with keys name, email, comment.",
                    $count
                ),
            ],
            [
                'role'    => 'user',
                'content' => "Title: {$title}\n\nContent: " . ($context['text'] ?? ''),
            ],
        ];

        return $prompt;
    }

    private static function buildFaq(array $context): array
    {
        $count    = (int) ($context['count'] ?? 5);
        $detailed = !empty($context['detailed']);
        $prompt   = self::basePrompt('faq', $context);

        $prompt['messages'] = [
            [
                'role'    => 'system',
                'content' => "Create a FAQ section about the given topic. Rules:\n1. Detect the language of the topic and write in that language\n2. Create {$count} questions and answers\n3. Use WordPress shortcode structure:\n[kanews-accordion]\n[kanews-collapse title=\"Question?\"]Answer[/kanews-collapse]\n[/kanews-accordion]\n4. " . ($detailed ? 'Provide detailed answers.' : 'Keep answers concise.') . "\n5. Use relevant key terms naturally in questions.",
            ],
            [
                'role'    => 'user',
                'content' => (string) ($context['text'] ?? ''),
            ],
        ];

        return $prompt;
    }

    private static function buildParaphrase(array $context): array
    {
        $level             = $context['level'] ?? 'medium';
        $preserveKeywords  = !empty($context['preserve_keywords']);
        $preserveStructure = !empty($context['preserve_structure']);
        $improveSeo        = !empty($context['improve_seo']);

        $levelGuide = [
            'light'  => "Make minimal changes to the text while maintaining its original meaning. Keep sentence structure similar and replace some words with synonyms.",
            'medium' => "Make moderate changes to the text while preserving its core message. Rewrite sentences with different structures and use synonyms for most words.",
            'high'   => "Completely rewrite the text while preserving its core message. Create entirely new sentence structures and use different vocabulary throughout.",
        ];

        $prompt = self::basePrompt('paraphrase', $context);
        $prompt['messages'] = [
            [
                'role'    => 'system',
                'content' => "You are a professional content rewriter. {$levelGuide[$level]}\n\n" .
                    ($preserveKeywords
                        ? "IMPORTANT: Identify and preserve all SEO keywords from the original text."
                        : "You may change all words, including keywords.") . "\n" .
                    ($preserveStructure
                        ? "Maintain the same overall structure, headings, and paragraph organization."
                        : "You may reorganize the content structure as needed.") . "\n" .
                    ($improveSeo
                        ? "Additionally, optimize the content for SEO by improving readability and keyword placement."
                        : '') . "\n\n" .
                    "HTML RULES:\n- Preserve all HTML tags, shortcodes, classes, IDs, and inline styles exactly as they are.\n- Do not modify <img> tags or their attributes.\n- Maintain all links and media.\n- Return the complete paraphrased content with original formatting.\n- Detect the language of the content and maintain the same language.",
            ],
            [
                'role'    => 'user',
                'content' => "Title: " . ($context['title'] ?? '') . "\n\nContent to paraphrase:\n" . ($context['text'] ?? ''),
            ],
        ];

        return $prompt;
    }

    private static function buildArticle(array $context): array
    {
        $style         = $context['style'] ?? 'news';
        $useList       = !empty($context['use_list']);
        $use5w1h       = !empty($context['use_5w1h']);
        $addFaq        = !empty($context['add_faq']);
        $language      = $context['language'] ?? 'auto';
        $useTables     = !empty($context['use_tables']);
        $notes         = $context['notes'] ?? '';
        $topic         = $context['topic'] ?? '';

        $styleGuides = [
            'news'        => 'Write a news article focusing on facts and current events.',
            'analysis'    => 'Create an analytical piece with data-driven insights and expert perspectives.',
            'interview'   => 'Format as an interview with expert Q&A structure.',
            'opinion'     => 'Write an opinion piece with clear arguments and supporting evidence.',
            'custom-news' => 'Create a unique custom news article.',
            'guide'       => 'Create a practical guide with clear steps and actionable advice.',
            'review'      => 'Write a balanced review covering pros, cons and detailed evaluation.',
            'list'        => 'Use a numbered list with informative and guiding tone.',
            'clickbait'   => "Write in clickbait news style with dramatic titles, suspense, short paragraphs, question-based subheadings, and provide the definitive answer in the final section whose heading is the main question in ALL CAPS.",
        ];

        $prompt = self::basePrompt('article', $context);
        $languageDirective = $language === 'auto'
            ? 'Write everything in the language matching the topic.'
            : "Write everything in {$language}.";

        $bodyDirectives = [
            $styleGuides[$style] ?? $styleGuides['news'],
            "<p class=\"has-medium-font-size\">Engaging introduction with naturally emphasized key terms</p>",
            "Use HTML tags in an SEO friendly manner (<strong>, <em>, headings).",
            $use5w1h
                ? "Create hierarchical subheadings using the 5W1H method with HTML heading tags."
                : "Create hierarchical subheadings with <h2>-<h4> tags.",
            $useTables
                ? "Include a relevant comparison table where appropriate:\n<table class=\"wp-table is-style-stripes\"><thead><tr><th>Compare</th></tr></thead><tbody><tr><td>Data</td></tr></tbody></table>"
                : '',
            $useList
                ? "Include relevant lists where appropriate:\n<ul><li>List item</li></ul>"
                : '',
            "<h2>Conclusion heading in article language</h2>\n- Summarize key points\n- Provide final thoughts",
            $addFaq
                ? "<h2>FAQ heading in article language</h2>\n[kanews-accordion]\n- Create 4-6 relevant questions and answers\n[kanews-collapse title=\"Question?\"]Answer[/kanews-collapse]\n[/kanews-accordion]"
                : '',
            $languageDirective,
            "Never mix languages. Use <h1>-<h4> tags for headings. Write a long, detailed answer adapted to topic complexity.",
            !empty($notes) ? "ADDITIONAL INSTRUCTIONS:\n{$notes}" : '',
        ];

        $prompt['messages'] = [
            [
                'role'    => 'system',
                'content' => implode("\n\n", array_filter($bodyDirectives)),
            ],
            [
                'role'    => 'user',
                'content' => "Create a {$style} article about: {$topic}",
            ],
        ];

        return $prompt;
    }

    private static function buildTranslate(array $context): array
    {
        $target = $context['target_language'] ?? 'en';
        $translateTitle = !empty($context['translate_title']);
        $title = $context['title'] ?? '';
        $languageNames = [
            'tr' => 'Turkish','en' => 'English','de' => 'German','fr' => 'French',
            'es' => 'Spanish','it' => 'Italian','ru' => 'Russian','ar' => 'Arabic',
            'pt' => 'Portuguese','zh' => 'Chinese','ja' => 'Japanese','ko' => 'Korean',
            'nl' => 'Dutch','pl' => 'Polish','sv' => 'Swedish','da' => 'Danish',
            'fi' => 'Finnish','no' => 'Norwegian','cs' => 'Czech','hu' => 'Hungarian',
            'ro' => 'Romanian','bg' => 'Bulgarian','hr' => 'Croatian','sk' => 'Slovak',
            'sl' => 'Slovenian','el' => 'Greek','he' => 'Hebrew','th' => 'Thai',
            'vi' => 'Vietnamese','id' => 'Indonesian','ms' => 'Malay','hi' => 'Hindi',
            'uk' => 'Ukrainian',
        ];
        $languageName = $languageNames[$target] ?? 'English';

        $titleInstruction = $translateTitle
            ? "IMPORTANT: Translate the article title to {$languageName} and place it as the FIRST LINE of your response, preceded by 'TITLE: '."
            : "IMPORTANT: Do NOT translate the title. Only translate the article content.";

        $prompt = self::basePrompt('translate', $context);
        $prompt['messages'] = [
            [
                'role'    => 'system',
                'content' => "You are a professional translator. {$titleInstruction}\n\nRules:\n- Translate ONLY the visible text content. Do not touch HTML tags, attributes, or shortcodes.\n- Keep all <img> tags and shortcodes unchanged.\n- Preserve all HTML formatting, classes, IDs, links, numbers, dates, and statistics.\n- Return the complete translated content with original HTML structure.\n- Use natural, fluent {$languageName} suitable for news content.",
            ],
            [
                'role'    => 'user',
                'content' => "Title: {$title}\n\nContent to translate:\n" . ($context['text'] ?? ''),
            ],
        ];

        return $prompt;
    }

    private static function buildNewsBot(array $context): array
    {
        $siteName        = get_bloginfo('name');
        $title           = $context['title'] ?? '';
        $sourceUrl       = $context['source_url'] ?? '';
        $flags           = $context['flags'] ?? [];
        $categoryChoices = trim((string) ($context['categories'] ?? ''));

        $additional = [];

        $additional[] = !empty($flags['use_5w1h'])
            ? "- Where applicable, organize subheadings with 5W1H using proper heading tags."
            : "- Create clear, topic-relevant subheadings using <h2>/<h3> tags.";
        if (!empty($flags['use_tables'])) {
            $additional[] = "- Include one concise HTML table for comparisons when relevant.";
        }
        if (!empty($flags['use_list'])) {
            $additional[] = "- Include short unordered lists (<ul><li>) to improve readability when needed.";
        }
        if (!empty($flags['add_faq'])) {
            $additional[] = "- Add an FAQ section at the end with 3–5 Q&A using WordPress shortcodes.";
        }

        $prompt = self::basePrompt('news-bot', $context);
        $prompt['messages'] = [
            [
                'role'    => 'system',
                'content' => "You are a senior news editor for {$siteName}. Rewrite the provided article as a fresh, original story while strictly preserving factual accuracy.\n\nLANGUAGE\n- Detect the source language and write 100% in the same language.\n\nGENRE ADAPTATION\n1) Classify the story into one genre (breaking, analysis, sports, finance/markets, technology/product, politics/policy, culture/entertainment).\n2) Adapt tone, structure, and details to that genre.\n3) Vary presentation to avoid uniform output.\n\nQUESTION HEADLINES\n- If the headline is a question, answer it clearly in the first two paragraphs and add a final <h2> section repeating the exact question followed by the definitive answer.\n\nOUTPUT FORMAT\n- First line: TITLE: [concise, SEO-friendly headline under ~70 chars]\n- Blank line, then article body in HTML only (<p>, <h2>, <h3>, <ul>, <li>, <strong>, <em>)\n- Include key data (scores, % moves, dates, prices) early\n- Aim for roughly 400–700 words unless topic needs more\n- No <h1> tags, no source URLs, no AI mentions\n" . implode("\n", $additional) . "\n\nCATEGORY SELECTION\n- Available WordPress category slugs: {$categoryChoices}\n- You MUST choose exactly ONE slug from this list.\n- Do NOT invent new slugs.\n- If you are unsure, pick the closest matching slug.\n- After the body, output on a separate final line: CATEGORY: [slug]",
            ],
            [
                'role'    => 'user',
                'content' => "Original article title: {$title}\nSource URL: {$sourceUrl}\n\nFull article:\n" . ($context['text'] ?? ''),
            ],
        ];

        return $prompt;
    }
}

