// prompts/templates.ts

import {ContentStyle} from "../enum/style.enum";
import {ContentTone} from "../enum/tone.enum";
import {Platform} from "../enum/platform.enum";
import {WriterPromptParams} from "../interfaces/writer-prompt-params.interface";
import {Language} from "../../../common/interfaces/language.prompt.interface";
import {PostLength} from "../enum/post-length.enum";
// export type Language = 'en' | 'vi' | 'ja' | 'ko' | 'jp' | 'kr' | 'vn';

// ============================================================
// LANGUAGE LABELS (dùng cho lock ngôn ngữ)
// ============================================================
export const LANGUAGE_NAMES: Record<Language, string> = {
    en: 'English',
    vi: 'Vietnamese (Tiếng Việt)',
    ja: 'Japanese (日本語)',
    ko: 'Korean (한국어)',
    cn: 'Chinese (中国人)',
};

// Native instructions để lock ngôn ngữ chắc chắn
export const LANGUAGE_LOCK: Record<Language, string> = {
    en: 'Output language: English ONLY. Do not use other languages.',
    cn: '输出语言：仅限中文。不会使用其他语言。',
    vi: 'Ngôn ngữ output: CHỈ Tiếng Việt. Không dùng ngôn ngữ khác.',
    ja: '出力言語: 日本語のみ。他の言語は使用しないこと。',
    ko: '출력 언어: 한국어만 사용. 다른 언어 사용 금지.',
};

export const STYLE_HINTS_TELEGRAM_BUTTON = {
    [ContentStyle.GENERAL]: {
        text: 'GENERAL'
    },
    [ContentStyle.CRYPTO]: {
        text: 'Crypto/Web3'
    },
    [ContentStyle.BREAKING_NEWS]: {
        text: 'Breaking news'
    },
    [ContentStyle.TECH]: {
        text: 'Tech-savvy'
    },
    [ContentStyle.FINANCE]: {
        text: 'Financial'
    },
    [ContentStyle.LIFESTYLE]: {
        text: 'Life style'
    },
    [ContentStyle.MEME]: {
        text: 'Meme'
    },
    [ContentStyle.EDUCATIONAL]: {
        text: 'Education'
    },
}

export const STYLE_HINTS: Record<ContentStyle, string> = {
    [ContentStyle.CRYPTO]: 'Crypto/Web3 tone. Use terms: bullish, alpha, gm, LFG. Add $TICKER, emojis 🚀📈. Degen but credible.',
    [ContentStyle.BREAKING_NEWS]: 'Breaking news format. Start with 🚨 BREAKING. Concise facts. Who/What/When. No fluff.',
    [ContentStyle.TECH]: 'Tech-savvy. Clear, confident. Mention specifics (tools, versions). Minimal hype.',
    [ContentStyle.FINANCE]: 'Financial, data-driven. Numbers, %, market terms. Neutral professional.',
    [ContentStyle.LIFESTYLE]: 'Warm, relatable, human. Light emojis. Story-driven.',
    [ContentStyle.MEME]: 'Funny, meme-ish, punchy. One-liner energy. Reference internet culture. Can use "[X] but actually [Y]" format',
    [ContentStyle.EDUCATIONAL]: 'Teach clearly. Structure: hook → insight → takeaway. Use analogies. Avoid jargon unless explained.',
    [ContentStyle.GENERAL]: 'Clear, engaging, neutral.',
    [ContentStyle.OPINION]: 'First-person opinion. Bold take. "I think / Hot take:". Invites debate.',
    [ContentStyle.STORYTELLING]: 'Narrative arc. Hook with tension → build → resolution. Personal or case-study.',
    [ContentStyle.THREAD]: 'Thread format. Start with hook tweet. Each point numbered. End with CTA or summary.',
};

export const TONE_HINTS_TELEGRAM_BUTTON = {
    [ContentTone.PROFESSIONAL]: {text: 'chuyên nghiệp, rõ ràng, đáng tin cậy'},
    [ContentTone.CASUAL]: {text: 'Giản dị,thân thiện'},
    [ContentTone.HYPE]: {text: 'Hype-Hào hứng,tràn đầy năng lượng'},
    [ContentTone.URGENT]: {text: 'urgent'},
    [ContentTone.HUMOROUS]: {text: 'Dí dỏm, hài hước'},
    [ContentTone.INFORMATIVE]: {text: 'Thông tin, chính xác'},
    [ContentStyle.OPINION]: {text: 'Quan điểm táo bạo. \n"Tôi nghĩ / Quan điểm gây tranh cãi:". Mời gọi tranh luận.'},
    [ContentStyle.STORYTELLING]: {text: 'STORYTELLING-Cấu trúc tự sự. Mở đầu bằng sự căng thẳng → phát triển → kết thúc.\n Có thể là câu chuyện cá nhân hoặc nghiên cứu trường hợp.'},
    [ContentStyle.THREAD]: {text: 'THREAD-Bắt đầu bằng một tweet thu hút sự chú ý. \nMỗi điểm được đánh số. \nKết thúc bằng lời kêu gọi hành động (CTA) hoặc tóm tắt.'},
}
export const TONE_HINTS: Record<ContentTone, string> = {
    [ContentTone.PROFESSIONAL]: 'professional, clear, credible',
    [ContentTone.CASUAL]: 'casual, friendly',
    [ContentTone.HYPE]: 'hyped, energetic',
    [ContentTone.URGENT]: 'urgent, attention-grabbing',
    [ContentTone.HUMOROUS]: 'witty, humorous',
    [ContentTone.INFORMATIVE]: 'informative, factual',
    [ContentTone.EMPATHETIC]: 'empathetic, emotionally aware, validating',
    [ContentTone.PROVOCATIVE]: 'thought-provoking, slightly controversial, challenges assumptions',
    [ContentTone.AUTHORITATIVE]: 'confident, commanding, expert-voice',
};

// export const PLATFORM_RULES: Record<Platform, string> = {
//     [Platform.X]: 'Max 420 chars. 2-5 hashtags. Hook in first line. No markdown.',
//     [Platform.FACEBOOK]: '400-800 chars. Can use line breaks. 2-5 hashtags. Engaging hook + CTA.',
// };
export const PLATFORM_RULES: Record<Platform, {
    short: string;
    detailed: (minChars: number, maxChars: number) => string;
}> = {
    [Platform.X]: {
        short: 'Max 420 chars. 2-5 hashtags. Hook first line. No markdown.',
        detailed: (min, max) =>
            `Length: ${min}-${max} characters (aim for ~${Math.floor((min + max) / 2)}). ` +
            `Use ALL available space to deliver maximum value. ` +
            `2-5 hashtags. Strong hook in first line. No markdown.`,
    },
    [Platform.FACEBOOK]: {
        short: '400-1200 chars. Hook + body + CTA.',
        detailed: (min, max) =>
            `Length: ${min}-${max} characters (aim for ~${Math.floor((min + max) / 2)}). ` +
            `Write a FULL post: strong hook → 2-4 paragraphs of value → clear CTA. ` +
            `Use line breaks for readability. 2-5 relevant hashtags at end.`,
    },
};

/**
 * Hướng dẫn structure theo length — QUAN TRỌNG để GPT không viết lan man.
 */
export const LENGTH_STRUCTURE_HINTS: Record<PostLength, {
    en: string;
    vi: string;
    ja: string;
    ko: string;
}> = {
    [PostLength.SHORT]: {
        en: 'Single punchy statement. Hook + 1 key fact. No paragraphs. 1-2 hashtag',
        vi: 'Một câu punchy duy nhất. Hook + 1 điểm chính. Không xuống dòng. 1-2 hashtag',
        ja: '短く強烈な一文。フック + 要点1つ。段落分けなし。, 1-2ハッシュタグ',
        ko: '짧고 강렬한 한 문장. 훅 + 핵심 1개. 단락 없음., 1-2 해시태그',
    },
    [PostLength.MEDIUM]: {
        en: 'Structure: Hook line → 2-3 key points → brief takeaway. Use line breaks. 2-4 hashtag',
        vi: 'Cấu trúc: Câu hook → 2-3 điểm chính → kết luận ngắn. Dùng xuống dòng. 2-4 hashtag',
        ja: '構成: フック文 → 要点2-3個 → 短い結論。改行を使う。1-4ハッシュタグ',
        ko: '구조: 훅 문장 → 핵심 2-3개 → 짧은 결론. 줄바꿈 사용. 1-4 해시태그',
    },
    [PostLength.LONG]: {
        en: [
            'Structure: Strong hook (1 line) → Context (2-3 lines) → 3-4 key points with details → Analysis/implication → CTA or takeaway.',
            'Use line breaks between sections. Numbered or bulleted lists OK.',
            'This is a Premium long-form post — use the space to deliver REAL value, not fluff.',
            '2-4 hashtag'
        ].join(' '),
        vi: [
            'Cấu trúc: Hook mạnh (1 dòng) → Bối cảnh (2-3 dòng) → 3-4 điểm chính có chi tiết → Phân tích/ý nghĩa → CTA hoặc kết luận.',
            'Dùng xuống dòng giữa các phần. List đánh số hoặc bullet OK.',
            'Đây là long-form post Premium — dùng không gian để truyền tải GIÁ TRỊ THẬT, không nhồi chữ.',
            '2-4 hashtag'
        ].join(' '),
        ja: [
            '構成: 強いフック (1行) → 背景 (2-3行) → 詳細な要点3-4個 → 分析/示唆 → CTAまたは結論。',
            'セクション間は改行。番号付き・箇条書きOK。',
            'これはPremiumのロングフォーム投稿です。スペースを使って本当の価値を届けること。冗長にしない。',
            '1-4ハッシュタグ'
        ].join(' '),
        ko: [
            '구조: 강한 훅 (1줄) → 배경 (2-3줄) → 상세한 핵심 3-4개 → 분석/시사점 → CTA 또는 결론.',
            '섹션 간 줄바꿈. 번호/글머리 기호 OK.',
            'Premium 롱폼 게시물 — 공간을 활용해 진짜 가치 전달. 채우기식 금지.',
            '1-4 해시태그'
        ].join(' '),
    },
    [PostLength.EXTENDED]: {
        en: 'Mini-article format: headline-style hook → intro paragraph → 4-6 sections with subheadings → conclusion → CTA. Treat as authority-building content. 2-5 hashtag',
        vi: 'Format mini-article: hook kiểu tiêu đề → đoạn intro → 4-6 phần có subheading → kết luận → CTA. Coi như nội dung xây dựng authority. 2-5 hashtag',
        ja: 'ミニ記事形式: 見出し風フック → 導入段落 → 小見出し付き4-6セクション → 結論 → CTA。オーソリティ構築コンテンツとして扱う。, 2-5ハッシュタグ',
        ko: '미니 아티클 형식: 헤드라인형 훅 → 서론 → 소제목 있는 4-6 섹션 → 결론 → CTA. 권위 구축 콘텐츠로 취급. 2-5 해시태그',
    },
    [PostLength.ARTICLE]: {
        en: 'Full article: title → lede → 6-10 sections → detailed examples → strong conclusion. Write like a journalist or analyst.',
        vi: 'Bài viết đầy đủ: tiêu đề → lede → 6-10 phần → ví dụ chi tiết → kết luận mạnh. Viết như nhà báo/analyst.',
        ja: '完全な記事: タイトル → リード → 6-10セクション → 詳細な例 → 強い結論。ジャーナリストやアナリストのように書く。, 2-5ハッシュタグ',
        ko: '완전한 기사: 제목 → 리드 → 6-10 섹션 → 상세한 예시 → 강한 결론. 기자/애널리스트처럼 작성. 2-5 해시태그',
    },
};

/** System prompt cho writer - cực ngắn để tiết kiệm token */
export function buildWriterSystemPrompt(): string {
    return 'You are a social media copywriter. Write ONLY the post content, no explanations, no quotes, no preamble.';
}

/** User prompt compact */
export function buildGenericWriterPrompt(params: WriterPromptParams): {
    system: string;
    user: string;
} {
    // const budget = calculateLengthBudget(ctx.platform, ctx.language);
    //
    // const targetLanguage = LANGUAGE_NAMES[ctx.language] || LANGUAGE_NAMES['en'];
    // const parts = [
    //     `[Target Language: ${targetLanguage}]
    //         IMPORTANT: Your previous answer violated language rules.
    //         Rewrite strictly in ${targetLanguage} only.`,
    //     `Platform: ${ctx.platform.toUpperCase()}`,
    //     `${PLATFORM_RULES[ctx.platform].detailed(budget.minChars, budget.maxChars)}`,
    //     `Style: ${STYLE_HINTS[ctx.style]}`,
    //     `Tone: ${TONE_HINTS[ctx.tone]}`,
    //     `Language: ${LANGUAGE_NAMES[ctx.language] || LANGUAGE_NAMES['en']}`,
    //     `Topic: ${ctx.topic}`,
    //     `⚠️ Target length: ${budget.minChars}-${budget.maxChars} characters. Write a substantive post.`,
    // ];
    //
    // if (ctx.extraInstructions) parts.push(`Extra: ${ctx.extraInstructions}`);
    // parts.push('Output: the post only.');
    // if ([ContentStyle.CRYPTO, ContentStyle.FINANCE].includes(ctx.style)) {
    //     parts.push(`Append disclaimer: “\n ⚠️ This content is for informational purposes only, not financial advice. DYOR.”`)
    // }
    // return parts.join('\n');


    const structure = LENGTH_STRUCTURE_HINTS[params.postLength][params.language];

    const systemByLang: Record<Language, string> = {
        en: 'You are a social media copywriter. Write ONLY the post in English. No preamble. must have hashtag',
        cn: '你是社交媒体文案撰写员。请仅用中文撰写帖子正文，无需前言，但必须包含话题标签。',
        vi: 'Bạn là copywriter MXH. CHỈ viết bài post bằng Tiếng Việt. Không giải thích. phải có hashtag',
        ja: 'ソーシャルメディアのコピーライター。投稿文のみを日本語で出力。, ハッシュタグは必須です。',
        ko: '소셜미디어 카피라이터. 게시물만 한국어로 작성. 해시태그를 사용해야 합니다.',
    };
    const targetLanguage = LANGUAGE_NAMES[params.language] || LANGUAGE_NAMES['en'];

    const parts = [
        `[Target Language: ${targetLanguage}]
            IMPORTANT: Your previous answer violated language rules.
            Rewrite strictly in ${targetLanguage} only.`,
        `Platform: ${params.platform.toUpperCase()}`,
        `Target length: ${params.lengthRange.min}-${params.lengthRange.max} chars (aim ~${params.lengthRange.sweet})`,
        `Structure: ${structure}`,
        `Style: ${STYLE_HINTS[params.style]}`,
        `Tone: ${TONE_HINTS[params.tone]}`,
        `${LANGUAGE_LOCK[params.language]}`,
        `Topic: ${params.topic}`,
        params.extraInstructions ? `Extra: ${params.extraInstructions}` : '',
        `Output: the post only.`,
    ];
    if ([ContentStyle.CRYPTO, ContentStyle.FINANCE].includes(params.style)) {
        parts.push(`Append disclaimer: “\n⚠️ This content is for informational purposes only, not financial advice. DYOR.”`)
    }
    const user = parts.filter(Boolean).join('\n');

    return {system: systemByLang[params.language], user};

}

/** Reviewer prompt - ngắn gọn, chỉ trả về JSON */
export function buildReviewerPrompt(draft: string, platform: Platform, style: ContentStyle, language: string): string {
    const targetLanguage = LANGUAGE_NAMES[language] || LANGUAGE_NAMES['en'];

    return [
        `[Output MUST be in ${targetLanguage}. Do NOT translate.`,
        `Review this ${platform.toUpperCase()} post (style: ${style}).`,
        //`Rules: ${PLATFORM_RULES[platform]}`,
        `Fix: grammar, hook strength, length, clarity. Keep voice.`,
        `Return ONLY JSON: {"improved":"<final post>","notes":"<short notes>"}`,
        `---\n${draft}`,
    ].join('\n');
}

export const BREAKING_NEWS_TEMPLATES: Record<Language, {
    system: string;
    formatHint: string;
    prefix: string;
}> = {
    en: {
        system: 'You are a breaking news writer for X. Write ONLY the post. No preamble, no explanations, no quotes. must have hashtag',
        formatHint: '🚨 BREAKING: [headline]\\n\\n[1-2 key facts]\\n\\n[source/impact] \\n\\n[hashtag]',
        prefix: '🚨 BREAKING',
    },
    cn: {
        system: 'You are a breaking news writer for X. Write ONLY the post. No preamble, no explanations, no quotes. must have hashtag',
        formatHint: '🚨 BREAKING: [headline]\\n\\n[1-2 key facts]\\n\\n[source/impact] \\n\\n[hashtag]',
        prefix: '🚨 BREAKING',
    },
    vi: {
        system: 'Bạn là biên tập tin nóng cho X. CHỈ viết bài post bằng Tiếng Việt. Không giải thích, không trích dẫn.',
        formatHint: '🚨 NÓNG: [tiêu đề]\\n\\n[1-2 thông tin chính]\\n\\n[nguồn/tác động] \\n\\n[hashtag]',
        prefix: '🚨 NÓNG',
    },
    ja: {
        system: 'あなたはX用の速報ライターです。投稿文のみを日本語で出力してください。説明・引用符・前置きは一切不要です。',
        formatHint: '🚨【速報】[見出し]\\n\\n[主要な事実1-2点]\\n\\n[情報源/影響] \\n\\n[해시태그.]',
        prefix: '🚨【速報】',
    },
    ko: {
        system: 'X 속보 작성자입니다. 게시물만 한국어로 작성하세요. 설명, 인용부호, 서두 모두 금지.',
        formatHint: '🚨 [속보] [헤드라인]\\n\\n[핵심 사실 1-2개]\\n\\n[출처/영향] \\n\\n[해시태그.]',
        prefix: '🚨 [속보]',
    },
};

export function buildBreakingNewsPrompt(params: WriterPromptParams
): { system: string; user: string } {
    const tpl = BREAKING_NEWS_TEMPLATES[params.language];
    // const budget = calculateLengthBudget(params.platform, params.language);

    // const user = [
    //     `Raw news content:\n${params.rawContent}`,
    //     ``,
    //     `Rewrite for X (280 char max):`,
    //     `- Format hint: ${tpl.formatHint}`,
    //     `- Start with 🚨 BREAKING / 速報 / 속보 / NÓNG`,
    //     `- Keep facts accurate, NO fabrication`,
    //     `- Urgent tone but not clickbait`,
    //     `- 1-2 relevant hashtags`,
    //     params.extraInstructions ? `- Extra: ${params.extraInstructions}` : '',
    // ].filter(Boolean).join('\n');
    // const user = [
    //     `Raw news content:\n${params.topic}`,
    //     ``,
    //     `Rewrite for ${params.platform.toUpperCase()}:`,
    //     `- ${PLATFORM_RULES[params.platform].detailed(budget.minChars, budget.maxChars)}`,
    //     `- Format: ${tpl.formatHint}`,
    //     `- Start with: ${tpl.prefix}`,
    //     `- Tone: ${TONE_HINTS[params.tone]}`,
    //     `- ⚠️ Write a COMPLETE post, not a one-liner. Aim for ${budget.minChars}-${budget.maxChars} characters.`,
    //     `- Keep facts accurate, NO fabrication`,
    //     `- ${LANGUAGE_LOCK[params.language]}`,
    //     params.extraInstructions ? `- Extra: ${params.extraInstructions}` : '',
    //     ``,
    //     `Output: the post only.`,
    // ].filter(Boolean).join('\n');

    const structure = LENGTH_STRUCTURE_HINTS[params.postLength][params.language];

    const user = [
        `Raw news content:\n${params.topic}`,
        ``,
        `Rewrite for ${params.platform.toUpperCase()}:`,
        `- Target length: ${params.lengthRange.min}-${params.lengthRange.max} chars (aim ~${params.lengthRange.sweet})`,
        `- Structure: ${structure}`,
        `- Format: ${tpl.formatHint}`,
        `- Start with: ${tpl.prefix}`,
        `- Tone: ${TONE_HINTS[params.tone]}`,
        `- Keep facts accurate, NO fabrication`,
        `- ${LANGUAGE_LOCK[params.language]}`,
        params.extraInstructions ? `- Extra: ${params.extraInstructions}` : '',
        ``,
        `Output: the post only.`,
    ].filter(Boolean).join('\n');


    return {system: tpl.system, user};
}
