#!/usr/bin/env python3
"""
Auto-generate Prism i18n README copies from the main README.md.

Each i18n file is a FULL copy of the main README with:
  - Translated title line
  - Translated language-switcher label
  - Adjusted relative paths for the docs/i18n/ directory
  - Auto-generated source note

Triggered by:
  - GitHub Actions on README.md changes (update-i18n.yml)
  - Pre-commit hook when README.md is staged

Usage:
  python3 scripts/generate_i18n.py
"""

import os
import re
import sys

REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

LANGS = {
    "es": {"name": "Español",    "title": "🧠 Prism MCP — El Palacio Mental para Agentes de IA",          "label": "Idioma"},
    "fr": {"name": "Français",   "title": "🧠 Prism MCP — Le Palais Mental pour Agents IA",               "label": "Langue"},
    "pt": {"name": "Português",  "title": "🧠 Prism MCP — O Palácio Mental para Agentes de IA",           "label": "Idioma"},
    "ro": {"name": "Română",     "title": "🧠 Prism MCP — Palatul Minții pentru Agenți IA",               "label": "Limba"},
    "uk": {"name": "Українська", "title": "🧠 Prism MCP — Палац Розуму для AI Агентів",                   "label": "Мова"},
    "ru": {"name": "Русский",    "title": "🧠 Prism MCP — Дворец Разума для AI Агентов",                  "label": "Язык"},
    "de": {"name": "Deutsch",    "title": "🧠 Prism MCP — Der Gedankenpalast für KI-Agenten",             "label": "Sprache"},
    "ja": {"name": "日本語",      "title": "🧠 Prism MCP — AIエージェントのためのマインドパレス",              "label": "言語"},
    "ko": {"name": "한국어",      "title": "🧠 Prism MCP — AI 에이전트를 위한 마인드 팰리스",                "label": "언어"},
    "zh": {"name": "中文",        "title": "🧠 Prism MCP — AI代理的心智宫殿",                               "label": "语言"},
    "ar": {"name": "العربية",    "title": "🧠 Prism MCP — قصر العقل لوكلاء الذكاء الاصطناعي",            "label": "اللغة"},
}

# Language switcher with paths relative to docs/i18n/
I18N_LANG_SWITCHER = " · ".join(
    ["[English](../../README.md)"]
    + [f"[{v['name']}](README_{k}.md)" for k, v in LANGS.items()]
)


def adjust_paths(content: str) -> str:
    """Rewrite markdown link targets from repo-root-relative to docs/i18n/-relative."""

    # 1. i18n cross-references: docs/i18n/README_xx.md → README_xx.md
    content = content.replace("](docs/i18n/README_", "](README_")

    # 2. docs/ assets (images, guides): docs/foo → ../foo
    content = content.replace("](docs/", "](../")

    # 3. ./ relative paths → ../../  (repo root from docs/i18n/)
    content = content.replace("](./", "](../../")

    # 4. Root-level standalone files
    content = content.replace("](LICENSE)", "](../../LICENSE)")
    content = content.replace("](CONTRIBUTING.md)", "](../../CONTRIBUTING.md)")
    content = content.replace("](CHANGELOG.md", "](../../CHANGELOG.md")   # catches #anchor too
    content = content.replace("](ROADMAP.md)", "](../../ROADMAP.md)")
    content = content.replace("](README.md)", "](../../README.md)")

    # 5. Root-level directories
    for d in ("examples/", "supabase/", "src/", "tests/", "training/"):
        content = content.replace(f"]({d}", f"](../../{d}")

    return content


def generate(readme_text: str) -> dict[str, str]:
    """Return {lang_code: file_content} for every configured language."""
    results = {}

    for code, lang in LANGS.items():
        out = readme_text

        # --- translated title ---
        out = re.sub(
            r"^# 🧠 Prism MCP — The Mind Palace for AI Agents",
            f"# {lang['title']}",
            out,
            count=1,
        )

        # --- remove the generation comment (it's for the main README only) ---
        out = out.replace(
            "<!-- 🌐 Translations auto-generated by scripts/generate_i18n.py "
            "— triggered by GitHub Actions on README.md changes -->\n",
            "",
        )

        # --- translated language-switcher label + i18n-relative paths ---
        out = re.sub(
            r'🌐 \*\*Translate:\*\*[^\n]*',
            f"🌐 **{lang['label']}:** {I18N_LANG_SWITCHER}",
            out,
            count=1,
        )

        # --- insert auto-generated note after language switcher ---
        out = re.sub(
            r"(🌐 \*\*" + re.escape(lang["label"]) + r":\*\*[^\n]*\n)",
            r"\1\n> **Note:** This file is auto-generated from the "
            "[main README](../../README.md) by `scripts/generate_i18n.py`.\n",
            out,
            count=1,
        )

        # --- adjust all relative paths ---
        out = adjust_paths(out)

        results[code] = out

    return results


def main() -> None:
    readme_path = os.path.join(REPO_ROOT, "README.md")
    if not os.path.isfile(readme_path):
        print(f"ERROR: {readme_path} not found", file=sys.stderr)
        sys.exit(1)

    with open(readme_path, "r", encoding="utf-8") as f:
        readme_text = f.read()

    outdir = os.path.join(REPO_ROOT, "docs", "i18n")
    os.makedirs(outdir, exist_ok=True)

    files = generate(readme_text)
    for code, content in files.items():
        filepath = os.path.join(outdir, f"README_{code}.md")
        with open(filepath, "w", encoding="utf-8") as f:
            f.write(content)
        print(f"✅ README_{code}.md  ({len(content.splitlines())} lines)")

    print(f"\nGenerated {len(files)} i18n files in {outdir}")


if __name__ == "__main__":
    main()
