use crate::ctx::GenContext;
use crate::rng::Rng;

struct BzLang {
    templates: &'static [&'static str],
    verbs: &'static [&'static str],
    adjectives: &'static [&'static str],
    nouns: &'static [&'static str],
}

const EN: BzLang = BzLang {
    templates: &[
        "{verb} {adj} {noun}",
        "We need to {verb} {adj} {noun}",
        "Let's {verb} our {adj} {noun}",
        "Time to {verb} {adj} {noun} at scale",
        "How we {verb} {adj} {noun} in production",
        "{verb} {adj} {noun} or get left behind",
        "Why every startup should {verb} {adj} {noun}",
        "Nobody talks about {adj} {noun}",
        "Hot take: {adj} {noun} is the new {adj} {noun}",
        "{adj} {noun} will replace {adj} {noun}",
        "Raised ${amount} to {verb} {adj} {noun}",
        "Our {adj} {noun} just hit {amount} users",
        "Just ship {adj} {noun} already",
        "{adj} {noun} is eating the world",
    ],
    verbs: &[
        "leverage",
        "disrupt",
        "democratize",
        "unlock",
        "scale",
        "reimagine",
        "supercharge",
        "orchestrate",
        "fine-tune",
        "productionize",
        "vibe-code",
        "ship",
        "align",
        "ground",
        "accelerate",
        "optimize",
        "monetize",
        "synergize",
        "empower",
        "transform",
    ],
    adjectives: &[
        "AI-powered",
        "LLM-driven",
        "agentic",
        "RAG-enabled",
        "multimodal",
        "context-aware",
        "self-healing",
        "autonomous",
        "prompt-engineered",
        "GPU-accelerated",
        "enterprise-grade",
        "zero-shot",
        "vector-embedded",
        "transformer-based",
        "end-to-end",
        "open-source",
        "responsible",
        "cloud-native",
        "real-time",
        "blockchain-enabled",
    ],
    nouns: &[
        "pipelines",
        "ecosystems",
        "copilots",
        "agents",
        "embeddings",
        "guardrails",
        "alignment",
        "foundation models",
        "workflows",
        "inference",
        "hallucinations",
        "synthetic data",
        "reasoning chains",
        "context windows",
        "benchmarks",
        "moats",
        "paradigms",
        "solutions",
        "frameworks",
        "data flywheel",
    ],
};

// Russian dev slang: Russian verbs + English tech nouns
const RU: BzLang = BzLang {
    templates: &[
        "{verb} {adj} {noun}",
        "Пора {verb} {adj} {noun}",
        "Надо {verb} наши {adj} {noun}",
        "В проде пора {verb} {adj} {noun}",
        "Каждый стартап должен {verb} {adj} {noun}",
        "Никто не говорит про {adj} {noun}",
        "{adj} {noun} заменят {adj} {noun}",
        "Подняли ${amount} чтобы {verb} {adj} {noun}",
        "Наши {adj} {noun} набрали {amount} юзеров",
        "Просто шипни {adj} {noun} уже",
        "{adj} {noun} — это новые {adj} {noun}",
    ],
    verbs: &[
        "задеплоить",
        "заскейлить",
        "отоптимизить",
        "продакшенизировать",
        "зашипать",
        "замонетизить",
        "переосмыслить",
        "прокачать",
        "заалайнить",
        "оркестрировать",
        "завайбкодить",
        "демократизировать",
        "разлочить",
        "трансформировать",
        "автоматизировать",
    ],
    adjectives: &[
        "AI-powered",
        "LLM-driven",
        "агентные",
        "RAG-enabled",
        "мультимодальные",
        "self-healing",
        "автономные",
        "GPU-accelerated",
        "enterprise-grade",
        "zero-shot",
        "cloud-native",
        "real-time",
        "блокчейн",
        "open-source",
        "контекст-aware",
    ],
    nouns: &[
        "пайплайны",
        "экосистемы",
        "копайлоты",
        "агенты",
        "эмбеддинги",
        "гарлрейлы",
        "воркфлоу",
        "инференс",
        "галлюцинации",
        "синтетические данные",
        "бенчмарки",
        "фреймворки",
        "парадигмы",
        "солюшены",
        "контекстные окна",
        "дата-флайвил",
    ],
};

const DE: BzLang = BzLang {
    templates: &[
        "{verb} {adj} {noun}",
        "Wir muessen {adj} {noun} {verb}",
        "Zeit fuer {adj} {noun} im Scale",
        "Wie wir {adj} {noun} in Produktion {verb}",
        "Warum jedes Startup {adj} {noun} {verb} sollte",
        "Niemand spricht ueber {adj} {noun}",
        "{adj} {noun} wird {adj} {noun} ersetzen",
        "${amount} eingesammelt um {adj} {noun} zu {verb}",
        "Einfach {adj} {noun} shippen",
        "{adj} {noun} ist das neue {adj} {noun}",
    ],
    verbs: &[
        "skalieren",
        "disrupten",
        "demokratisieren",
        "optimieren",
        "monetarisieren",
        "orchestrieren",
        "transformieren",
        "beschleunigen",
        "shippen",
        "deployen",
        "automatisieren",
        "digitalisieren",
        "implementieren",
        "integrieren",
        "migrieren",
    ],
    adjectives: &[
        "KI-gestuetzte",
        "LLM-basierte",
        "agentische",
        "multimodale",
        "autonome",
        "GPU-beschleunigte",
        "enterprise-grade",
        "cloud-native",
        "Echtzeit",
        "blockchain-faehige",
        "zero-shot",
        "open-source",
        "kontextbewusste",
        "selbstheilende",
        "end-to-end",
    ],
    nouns: &[
        "Pipelines",
        "Oekosysteme",
        "Copiloten",
        "Agenten",
        "Embeddings",
        "Guardrails",
        "Workflows",
        "Inferenz",
        "Halluzinationen",
        "Benchmarks",
        "Paradigmen",
        "Loesungen",
        "Frameworks",
        "Datenmodelle",
        "Architektur",
        "Plattformen",
    ],
};

const ES: BzLang = BzLang {
    templates: &[
        "{verb} {adj} {noun}",
        "Necesitamos {verb} {adj} {noun}",
        "Es hora de {verb} {adj} {noun} a escala",
        "Como hacemos {verb} {adj} {noun} en produccion",
        "Por que todo startup debe {verb} {adj} {noun}",
        "Nadie habla de {adj} {noun}",
        "{adj} {noun} va a reemplazar {adj} {noun}",
        "Levantamos ${amount} para {verb} {adj} {noun}",
        "Solo shipea {adj} {noun} de una vez",
        "{adj} {noun} se esta comiendo el mundo",
    ],
    verbs: &[
        "escalar",
        "disrumpir",
        "democratizar",
        "desbloquear",
        "reimaginar",
        "potenciar",
        "orquestar",
        "optimizar",
        "monetizar",
        "shipear",
        "deployar",
        "transformar",
        "acelerar",
        "automatizar",
        "productivizar",
    ],
    adjectives: &[
        "potenciado por IA",
        "basado en LLM",
        "agentico",
        "multimodal",
        "autonomo",
        "acelerado por GPU",
        "enterprise-grade",
        "cloud-native",
        "en tiempo real",
        "blockchain-enabled",
        "zero-shot",
        "open-source",
        "context-aware",
        "self-healing",
        "end-to-end",
    ],
    nouns: &[
        "pipelines",
        "ecosistemas",
        "copilotos",
        "agentes",
        "embeddings",
        "guardrails",
        "workflows",
        "inferencia",
        "alucinaciones",
        "datos sinteticos",
        "benchmarks",
        "frameworks",
        "paradigmas",
        "soluciones",
        "modelos fundacionales",
        "plataformas",
    ],
};

// Ukrainian dev slang: Ukrainian verbs + English tech nouns
const UK: BzLang = BzLang {
    templates: &[
        "{verb} {adj} {noun}",
        "Треба {verb} {adj} {noun}",
        "Час {verb} наші {adj} {noun}",
        "В проді пора {verb} {adj} {noun}",
        "Кожен стартап має {verb} {adj} {noun}",
        "Ніхто не говорить про {adj} {noun}",
        "{adj} {noun} замінять {adj} {noun}",
        "Підняли ${amount} щоб {verb} {adj} {noun}",
        "Наші {adj} {noun} набрали {amount} юзерів",
        "Просто шипни {adj} {noun} вже",
        "{adj} {noun} — це нові {adj} {noun}",
    ],
    verbs: &[
        "задеплоїти",
        "заскейлити",
        "заоптимізити",
        "продакшенізувати",
        "зашипати",
        "замонетизувати",
        "переосмислити",
        "прокачати",
        "заелайнити",
        "оркеструвати",
        "завайбкодити",
        "демократизувати",
        "розлочити",
        "трансформувати",
        "автоматизувати",
    ],
    adjectives: &[
        "AI-powered",
        "LLM-driven",
        "агентні",
        "RAG-enabled",
        "мультимодальні",
        "self-healing",
        "автономні",
        "GPU-accelerated",
        "enterprise-grade",
        "zero-shot",
        "cloud-native",
        "real-time",
        "блокчейн",
        "open-source",
        "контекст-aware",
    ],
    nouns: &[
        "пайплайни",
        "екосистеми",
        "копайлоти",
        "агенти",
        "ембедінги",
        "гардрейли",
        "воркфлоу",
        "інференс",
        "галюцинації",
        "синтетичні дані",
        "бенчмарки",
        "фреймворки",
        "парадигми",
        "солюшени",
        "контекстні вікна",
        "дата-флайвіл",
    ],
};

// Belarusian dev slang: Belarusian verbs + English tech nouns
const BE: BzLang = BzLang {
    templates: &[
        "{verb} {adj} {noun}",
        "Трэба {verb} {adj} {noun}",
        "Час {verb} нашы {adj} {noun}",
        "У продзе пара {verb} {adj} {noun}",
        "Кожны стартап мусіць {verb} {adj} {noun}",
        "Ніхто не кажа пра {adj} {noun}",
        "{adj} {noun} заменяць {adj} {noun}",
        "Падняли ${amount} каб {verb} {adj} {noun}",
        "Нашы {adj} {noun} набралі {amount} юзераў",
        "Проста шыпні {adj} {noun} ужо",
        "{adj} {noun} — гэта новыя {adj} {noun}",
    ],
    verbs: &[
        "задэплоіць",
        "заскейліць",
        "заоптымізаваць",
        "прадакшэнізаваць",
        "зашыпаць",
        "замонетызаваць",
        "пераасэнсаваць",
        "пракачаць",
        "заэлайніць",
        "аркестраваць",
        "завайбкодзіць",
        "дэмакратызаваць",
        "разлочыць",
        "трансфармаваць",
        "аўтаматызаваць",
    ],
    adjectives: &[
        "AI-powered",
        "LLM-driven",
        "агентныя",
        "RAG-enabled",
        "мультымадальныя",
        "self-healing",
        "аўтаномныя",
        "GPU-accelerated",
        "enterprise-grade",
        "zero-shot",
        "cloud-native",
        "real-time",
        "блокчэйн",
        "open-source",
        "кантэкст-aware",
    ],
    nouns: &[
        "пайплайны",
        "экасістэмы",
        "капайлоты",
        "агенты",
        "эмбедзінгі",
        "гардрэйлы",
        "воркфлоу",
        "інферэнс",
        "галюцынацыі",
        "сінтэтычныя дадзеныя",
        "бенчмаркі",
        "фрэймворкі",
        "парадыгмы",
        "салюшэны",
        "кантэкстныя вокны",
        "дата-флайвіл",
    ],
};

// Serbian dev slang: Serbian verbs + English tech nouns (Cyrillic)
const SR: BzLang = BzLang {
    templates: &[
        "{verb} {adj} {noun}",
        "Морамо да {verb} {adj} {noun}",
        "Време је да {verb} наше {adj} {noun}",
        "У проду треба {verb} {adj} {noun}",
        "Сваки стартап мора да {verb} {adj} {noun}",
        "Нико не прича о {adj} {noun}",
        "{adj} {noun} ће заменити {adj} {noun}",
        "Подигли ${amount} да {verb} {adj} {noun}",
        "Наши {adj} {noun} имају {amount} корисника",
        "Само шипуј {adj} {noun} већ једном",
        "{adj} {noun} — то су нови {adj} {noun}",
    ],
    verbs: &[
        "деплојујемо",
        "скејлујемо",
        "оптимизујемо",
        "продакшенизујемо",
        "шипујемо",
        "монетизујемо",
        "преосмислимо",
        "унапредимо",
        "алајнујемо",
        "оркестрирамо",
        "вајбкодирамо",
        "демократизујемо",
        "откључамо",
        "трансформишемо",
        "аутоматизујемо",
    ],
    adjectives: &[
        "AI-powered",
        "LLM-driven",
        "агентне",
        "RAG-enabled",
        "мултимодалне",
        "self-healing",
        "аутономне",
        "GPU-accelerated",
        "enterprise-grade",
        "zero-shot",
        "cloud-native",
        "real-time",
        "блокчејн",
        "open-source",
        "контекст-aware",
    ],
    nouns: &[
        "пајплајне",
        "екосистеме",
        "копајлоте",
        "агенте",
        "ембединге",
        "гардрејле",
        "воркфлоу",
        "инференс",
        "халуцинације",
        "синтетичке податке",
        "бенчмарке",
        "фрејмворке",
        "парадигме",
        "солуције",
        "контекстне прозоре",
        "дата-флајвил",
    ],
};

// Brazilian Portuguese dev slang
const PT_BR: BzLang = BzLang {
    templates: &[
        "{verb} {adj} {noun}",
        "Precisamos {verb} {adj} {noun}",
        "Bora {verb} nossas {adj} {noun}",
        "Hora de {verb} {adj} {noun} em escala",
        "Como a gente faz {verb} {adj} {noun} em prod",
        "Todo startup precisa {verb} {adj} {noun}",
        "Ninguem fala sobre {adj} {noun}",
        "{adj} {noun} vai substituir {adj} {noun}",
        "Levantamos ${amount} pra {verb} {adj} {noun}",
        "Nossas {adj} {noun} bateram {amount} usuarios",
        "So shipa {adj} {noun} logo",
        "{adj} {noun} ta comendo o mundo",
        "{adj} {noun} e o novo {adj} {noun}",
    ],
    verbs: &[
        "escalar",
        "disruptar",
        "democratizar",
        "destravar",
        "reimaginar",
        "turbinar",
        "orquestrar",
        "otimizar",
        "monetizar",
        "shipar",
        "deployar",
        "transformar",
        "acelerar",
        "automatizar",
        "produtizar",
        "vibe-codar",
    ],
    adjectives: &[
        "AI-powered",
        "LLM-driven",
        "agenticas",
        "RAG-enabled",
        "multimodais",
        "self-healing",
        "autonomas",
        "GPU-accelerated",
        "enterprise-grade",
        "zero-shot",
        "cloud-native",
        "real-time",
        "blockchain",
        "open-source",
        "context-aware",
    ],
    nouns: &[
        "pipelines",
        "ecossistemas",
        "copilots",
        "agentes",
        "embeddings",
        "guardrails",
        "workflows",
        "inferencia",
        "alucinacoes",
        "dados sinteticos",
        "benchmarks",
        "frameworks",
        "paradigmas",
        "solucoes",
        "janelas de contexto",
        "data flywheel",
    ],
};

const JA: BzLang = BzLang {
    templates: &[
        "{adj}{noun}を{verb}",
        "{adj}{noun}を{verb}する時代",
        "なぜ全てのスタートアップが{adj}{noun}を{verb}すべきか",
        "{adj}{noun}が{adj}{noun}を置き換える",
        "${amount}調達して{adj}{noun}を{verb}",
        "{adj}{noun}は世界を変える",
        "今すぐ{adj}{noun}をシップしよう",
        "誰も{adj}{noun}について語らない",
        "{adj}{noun}が{amount}ユーザーを突破",
        "本番環境で{adj}{noun}を{verb}する方法",
    ],
    verbs: &[
        "スケール",
        "ディスラプト",
        "民主化",
        "最適化",
        "マネタイズ",
        "オーケストレート",
        "トランスフォーム",
        "加速",
        "デプロイ",
        "シップ",
        "自動化",
        "プロダクション化",
        "デジタル化",
        "イノベート",
        "レバレッジ",
    ],
    adjectives: &[
        "AI駆動の",
        "LLMベースの",
        "エージェント型",
        "マルチモーダル",
        "自律型",
        "GPU加速の",
        "エンタープライズ級",
        "クラウドネイティブ",
        "リアルタイム",
        "ブロックチェーン対応",
        "ゼロショット",
        "オープンソース",
        "コンテキスト認識",
        "セルフヒーリング",
        "エンドツーエンド",
    ],
    nouns: &[
        "パイプライン",
        "エコシステム",
        "コパイロット",
        "エージェント",
        "エンベディング",
        "ガードレール",
        "ワークフロー",
        "推論",
        "ハルシネーション",
        "合成データ",
        "ベンチマーク",
        "フレームワーク",
        "パラダイム",
        "ソリューション",
        "基盤モデル",
        "プラットフォーム",
    ],
};

const AMOUNTS: &[&str] =
    &["4.2M", "16M", "100M", "1.2B", "50K", "2.7M", "420K", "69M", "500K", "10M"];

fn lang_for(code: &str) -> &'static BzLang {
    match code {
        "ru" | "bg" | "hr" | "sl" | "pl" | "cs" | "sk" => &RU,
        "uk" => &UK,
        "be" => &BE,
        "sr" => &SR,
        "pt" | "pt-br" => &PT_BR,
        "de" | "de-at" | "lb" => &DE,
        "es" | "mx" | "co" | "cl" | "pe" | "ec" | "uy" | "ve" => &ES,
        "ja" => &JA,
        _ => &EN,
    }
}

fn pick<'a>(rng: &mut Rng, pool: &'a [&'a str]) -> &'a str {
    pool[rng.urange(0, pool.len() - 1)]
}

fn capitalize(s: &str) -> String {
    let mut c = s.chars();
    match c.next() {
        None => String::new(),
        Some(f) => {
            let mut out = String::with_capacity(s.len());
            for u in f.to_uppercase() {
                out.push(u);
            }
            out.push_str(c.as_str());
            out
        }
    }
}

pub fn gen(ctx: &mut GenContext<'_>, buf: &mut String) {
    buf.push_str(&gen_bz_inner(ctx));
}
fn gen_bz_inner(ctx: &mut GenContext<'_>) -> String {
    let lang = if ctx.locales.len() <= 5 {
        let loc = ctx.locale();
        lang_for(loc.code)
    } else {
        &EN
    };
    let tpl = lang.templates[ctx.rng.urange(0, lang.templates.len() - 1)];
    let mut out = String::with_capacity(tpl.len() + 40);
    let mut rest = tpl;
    while let Some(pos) = rest.find('{') {
        out.push_str(&rest[..pos]);
        rest = &rest[pos + 1..];
        if let Some(end) = rest.find('}') {
            let key = &rest[..end];
            let replacement = match key {
                "verb" => pick(&mut ctx.rng, lang.verbs),
                "adj" => pick(&mut ctx.rng, lang.adjectives),
                "noun" => pick(&mut ctx.rng, lang.nouns),
                "amount" => pick(&mut ctx.rng, AMOUNTS),
                _ => key,
            };
            out.push_str(replacement);
            rest = &rest[end + 1..];
        } else {
            out.push('{');
        }
    }
    out.push_str(rest);
    capitalize(&out)
}
