"""Guard Files editor toolbar labels and alignment actions.

This prevents raw language-key text such as align_center_btn / align_right_btn
from leaking into the document editor toolbar.
"""
from __future__ import annotations

import json
from datetime import datetime
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
REPORT = ROOT / "data" / "files_toolbar_i18n_latest.json"


def main() -> int:
    files_page = (ROOT / "pages" / "files_page.py").read_text(encoding="utf-8", errors="ignore")
    issues: list[str] = []
    required_markers = {
        "toolbar_items_present": "toolbar_items = [" in files_page,
        "align_left_icon": '"≡←"' in files_page and "self.align_left" in files_page,
        "align_center_icon": '"≡↔"' in files_page and "self.align_center" in files_page,
        "align_right_icon": '"≡→"' in files_page and "self.align_right" in files_page,
        "alignment_tooltips": 'ToolTip(btn, lambda text=item["tooltip"]: text)' in files_page,
        "raw_key_not_used_as_button_label": '(self.app.t("align_center_btn"), self.align_center)' not in files_page and '(self.app.t("align_right_btn"), self.align_right)' not in files_page,
    }
    for name, ok in required_markers.items():
        if not ok:
            issues.append(name)
    for lang in ("zh_CN", "en_US", "id_ID"):
        try:
            payload = json.loads((ROOT / "lang" / f"{lang}.json").read_text(encoding="utf-8"))
        except Exception as exc:
            issues.append(f"{lang}_json_load_failed:{exc}")
            continue
        for key in ("align_left_btn", "align_center_btn", "align_right_btn"):
            value = str(payload.get(key, "")).strip()
            if not value or value == key:
                issues.append(f"{lang}_{key}_invalid")
    payload = {
        "time": datetime.now().isoformat(timespec="seconds"),
        "status": "OK" if not issues else "FAILED",
        "issues": issues,
        "checks": required_markers,
    }
    REPORT.parent.mkdir(parents=True, exist_ok=True)
    REPORT.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    print("Files toolbar i18n guard", payload["status"])
    for issue in issues:
        print("-", issue)
    return 0 if not issues else 1


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