import zipfile
import csv
import os
import shutil
from pathlib import Path
import argparse
import subprocess
import json

ENCODING = "utf-8"

BASE_DIR = Path("Mission")
MIZ_DIR = BASE_DIR / "miz"
CSV_DIR = BASE_DIR / "csv"
WORK_DIR = BASE_DIR / "export"
IMPORT_DIR = BASE_DIR / "import"

DEFAULT_DICT = "l10n/DEFAULT/dictionary"

# ✅ Excel (TR) için doğru ayırıcı:
CSV_DELIM = ";"   # <-- BU OLMAZSA EXCEL A SÜTUNUNA YIĞAR

LANGUAGES = {
    "EN": "Text_EN",
    "TR": "Text_TR",
    "DE": "Text_DE",
    "FR": "Text_FR",
    "ES": "Text_ES",
    "IT": "Text_IT",
    "PL": "Text_PL",
    "RU": "Text_RU",
    "CN": "Text_CN",
    "JP": "Text_JP",
}

# ✅ Senin istediğin kolon sırası:
# A: (boş)
# B: Text_TR
# C: Text_EN
# D: Text_DE ...
EXPORT_COL_ORDER = ["EN", "TR", "DE", "FR", "ES", "IT", "PL", "RU", "CN", "JP"]

# ------------------------
# UTILS
# ------------------------

def unzip(miz, out):
    with zipfile.ZipFile(miz, "r") as z:
        z.extractall(out)

def zipdir(src, out):
    with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as z:
        for root, _, files in os.walk(src):
            for f in files:
                p = Path(root) / f
                z.write(p, p.relative_to(src))

def extract_with_lua(dictionary_path, out_json):
    subprocess.run(
        ["lua", "extract_dictionary.lua", str(dictionary_path), str(out_json)],
        check=True
    )
    with open(out_json, encoding="utf-8") as f:
        return json.load(f)

def open_csv_safely(path):
    for enc in ("utf-8", "utf-8-sig", "cp1254"):
        try:
            f = open(path, encoding=enc, newline="")
            f.read(1024)
            f.seek(0)
            return f
        except UnicodeDecodeError:
            continue
    raise RuntimeError("CSV encoding çözülemedi")

# ------------------------
# TEXT NORMALIZER
# ------------------------

def needs_arrow(key: str) -> bool:
    return (
        key.startswith("DictKey_subtitle_")
        or key.startswith("DictKey_ActionRadioText_")
        or key.startswith("DictKey_ActionText_")
        or key.startswith("DictKey_UnitName_")
        or key.startswith("DictKey_Sortie_")
        or key.startswith("DictKey_GroupName_")
        or key.startswith("DictKey_WptName_")
        or key.startswith("DictKey_descriptionNeutralsTask_")
        or key.startswith("DictKey_descriptionBlueTask_")
        or key.startswith("DictKey_descriptionText_")
    )

def normalize_text(key, text):
    if not text:
        return ""

    s = text.strip()

    if not needs_arrow(key):
        return s

    while s.startswith("→"):
        s = s[1:].strip()

    if "→" in s:
        left, right = s.split("→", 1)
        s = f"{left.strip()} : {right.strip()}"

    if ":" in s:
        left, right = s.split(":", 1)
        s = f"{left.strip()} : {right.strip()}"

    return f"→ {s}"

# ------------------------
# EXPORT
# ------------------------

def export_all():
    CSV_DIR.mkdir(parents=True, exist_ok=True)
    WORK_DIR.mkdir(parents=True, exist_ok=True)

    miz_files = list(MIZ_DIR.glob("*.miz"))
    if not miz_files:
        print("Hiç .miz bulunamadı")
        return

    for miz in miz_files:
        name = miz.stem
        work = WORK_DIR / name
        shutil.rmtree(work, ignore_errors=True)
        work.mkdir(parents=True)

        unzip(miz, work)

        dict_lua = work / DEFAULT_DICT
        if not dict_lua.exists():
            print(f"[SKIP] {name}")
            continue

        data = extract_with_lua(dict_lua, work / "dictionary.json")

        csv_path = CSV_DIR / f"{name}.csv"
        with open(csv_path, "w", newline="", encoding="utf-8") as f:
            writer = csv.writer(f, delimiter=CSV_DELIM)

            # ✅ HEADER: A boş, B=Text_EN, C=Text_TR...
            header = [""] + [LANGUAGES[c] for c in EXPORT_COL_ORDER]
            writer.writerow(header)

            for k, v in data.items():
                base = normalize_text(k, v)

                # A kolonu key
                row = [k]

                # B.. kolonları (sadece EN dolu, diğerleri boş kalsın istiyorsan)
                for code in EXPORT_COL_ORDER:
                    if code == "EN":
                        row.append(base)
                    else:
                        row.append("")
                writer.writerow(row)

        print(f"[OK] CSV EXPORT → {csv_path.name}")

# ------------------------
# IMPORT
# ------------------------

def import_all(lang):
    lang = lang.upper()
    if lang not in LANGUAGES:
        raise RuntimeError("Desteklenmeyen dil")

    IMPORT_DIR.mkdir(parents=True, exist_ok=True)

    for miz in MIZ_DIR.glob("*.miz"):
        name = miz.stem
        csv_path = CSV_DIR / f"{name}.csv"
        if not csv_path.exists():
            print(f"[SKIP] {name}")
            continue

        work = WORK_DIR / name
        shutil.rmtree(work, ignore_errors=True)
        work.mkdir(parents=True)

        unzip(miz, work)

        entries = []
        with open_csv_safely(csv_path) as f:
            reader = csv.DictReader(f, delimiter=CSV_DELIM)

            for row in reader:
                key = row[""]  # A sütunu başlığı boştu
                target_col = LANGUAGES[lang]

                text = (row.get(target_col) or "").strip()
                fallback_en = (row.get("Text_EN") or "").strip()
                final = text if text else fallback_en

                entries.append((key, final))

        out_dict = work / f"l10n/{lang}/dictionary"
        out_dict.parent.mkdir(parents=True, exist_ok=True)

        with open(out_dict, "w", encoding="utf-8") as f:
            f.write("dictionary = {\n")
            for k, t in entries:
                t = (t or "").replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
                f.write(f'    ["{k}"] = "{t}",\n')
            f.write("}\n")

        out_miz = IMPORT_DIR / f"{name}_{lang}.miz"
        zipdir(work, out_miz)

        print(f"[OK] IMPORT → {out_miz.name}")

# ------------------------
# MAIN
# ------------------------

def main():
    p = argparse.ArgumentParser("DCS Mission Translator")
    p.add_argument("cmd", choices=["csvexport", "mizimport"])
    p.add_argument("lang", nargs="?")

    args = p.parse_args()

    if args.cmd == "csvexport":
        export_all()
    else:
        if not args.lang:
            raise RuntimeError("Dil kodu gerekli (TR, DE, FR...)")
        import_all(args.lang)

if __name__ == "__main__":
    main()