"""Check language selector display rules.

Rules:
- Collapsed language buttons on login and logged-in header display short codes only: CN / EN / ID.
- Dropdown menu items display the full hybrid labels: CN-中文 / EN-English / ID-Indonesia.
"""
from __future__ import annotations

import argparse
import json
import re
from datetime import datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
REPORT_PATH = ROOT / "data" / "language_selector_display_latest.json"


def _version() -> str:
    text = (ROOT / "core" / "constants.py").read_text(encoding="utf-8", errors="ignore")
    match = re.search(r'APP_VERSION\s*=\s*"([^"]+)"', text)
    return match.group(1) if match else "unknown"


def build_report() -> dict:
    issues: list[str] = []
    app = (ROOT / "app.py").read_text(encoding="utf-8", errors="ignore")
    constants = (ROOT / "core" / "constants.py").read_text(encoding="utf-8", errors="ignore")

    required_constants = {
        'LANG_SHORT = {"zh_CN": "CN", "en_US": "EN", "id_ID": "ID"}': "short language code map",
        'LANG_DISP = {"zh_CN": "CN-中文", "en_US": "EN-English", "id_ID": "ID-Indonesia"}': "hybrid dropdown language map",
    }
    for marker, label in required_constants.items():
        if marker not in constants:
            issues.append(f"Missing or changed {label}: {marker}")

    required_app_markers = {
        'text=f"{LANG_SHORT.get(self.lang_code, \'ID\')} ▾"': "login collapsed language uses short code",
        'self.lang_var = tk.StringVar(value=LANG_SHORT.get(self.lang_code': "header language variable uses short code",
        'text=f"{LANG_SHORT.get(self.lang_code, self.lang_code[:2].upper())} ▾"': "header collapsed language uses short code",
        'items = [("zh_CN", LANG_DISP["zh_CN"]), ("en_US", LANG_DISP["en_US"]), ("id_ID", LANG_DISP["id_ID"])]': "dropdown menu uses hybrid labels",
        'for code, label in (("zh_CN", LANG_DISP["zh_CN"]), ("en_US", LANG_DISP["en_US"]), ("id_ID", LANG_DISP["id_ID"]))': "login dropdown uses hybrid labels",
    }
    for marker, label in required_app_markers.items():
        if marker not in app:
            issues.append(f"Missing marker: {label}")

    forbidden = {
        'text=f"{LANG_DISP.get(self.lang_code': "login collapsed language must not use full hybrid label",
        'text=f"{LANG_DISP[self.lang_code]} ▾"': "header collapsed language must not use full hybrid label",
        'self.lang_var = tk.StringVar(value=LANG_DISP': "header language variable must not store full hybrid label",
        'self.lang_btn.config(text=f"{LANG_DISP': "language refresh must not set full hybrid label on collapsed button",
        'compact_language_fallback": "CN / EN / ID only on tiny header layouts"': "old schema says short codes only in tiny layouts",
        'language_selector_style": "CN-中文 / EN-English / ID-Indonesia"': "old schema says collapsed selector uses hybrid style",
    }
    for marker, label in forbidden.items():
        if marker in app:
            issues.append(f"Forbidden marker in app.py: {label}")

    return {
        "checked_at": datetime.now().isoformat(timespec="seconds"),
        "version": _version(),
        "status": "OK" if not issues else "FAILED",
        "rule": {
            "collapsed_login_and_header": "CN / EN / ID",
            "dropdown_items": "CN-中文 / EN-English / ID-Indonesia",
        },
        "issues": issues,
    }


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--write-report", action="store_true")
    args = parser.parse_args()
    report = build_report()
    if args.write_report:
        REPORT_PATH.parent.mkdir(parents=True, exist_ok=True)
        REPORT_PATH.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
    print("NexaOffice Language Selector Display Check")
    print(f"- Version: {report['version']}")
    print(f"- Status: {report['status']}")
    if report["issues"]:
        for issue in report["issues"][:20]:
            print("  ", issue)
    if args.write_report:
        print(f"- Report: {REPORT_PATH.relative_to(ROOT)}")
    return 0 if report["status"] == "OK" else 1


if __name__ == "__main__":
    raise SystemExit(main())
