"""NexaOffice layout adaptation preflight.

This static check guards the UI against returning to fixed-width assumptions.
Run from project root:
    python tools/layout_adaptation_check.py --write-report
"""
from __future__ import annotations

import json
import re
import sys
from datetime import datetime
from pathlib import Path

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


def main() -> int:
    issues = []
    app_py = ROOT / "app.py"
    cal_py = ROOT / "pages" / "calendar_page.py"
    settings = {}

    app_text = app_py.read_text(encoding="utf-8", errors="ignore") if app_py.exists() else ""
    cal_text = cal_py.read_text(encoding="utf-8", errors="ignore") if cal_py.exists() else ""

    if "max(int(self.root.winfo_width()), 1220)" in app_text:
        issues.append("app.py still floors runtime width to 1220px")
    if "root.minsize(min(1040" in app_text:
        issues.append("app.py still uses the old high minimum window width")
    if "_update_runtime_layout_profile" not in app_text:
        issues.append("runtime layout profile helper missing")
    if "_apply_header_compaction" not in app_text:
        issues.append("header compaction helper missing")
    if "_apply_sidebar_compaction" not in app_text:
        issues.append("sidebar compaction helper missing")
    if "self._side_panel_collapsed" not in cal_text:
        issues.append("calendar year-view side panel collapse guard missing")
    if "width = max(int(width), 720)" not in cal_text:
        issues.append("calendar page does not use real narrow runtime width")
    if "month_count_segment.pack_forget" not in cal_text:
        issues.append("calendar toolbar does not compact month-count segment")
    if not (ROOT / "core" / "responsive.py").exists():
        issues.append("core/responsive.py runtime fit helpers missing")
    responsive_text = (ROOT / "core" / "responsive.py").read_text(encoding="utf-8", errors="ignore") if (ROOT / "core" / "responsive.py").exists() else ""
    if "clamp_ui_font_scale" not in responsive_text:
        issues.append("safe runtime font-scale clamp helper missing")
    if "collect_widget_fit_issues" not in responsive_text:
        issues.append("runtime widget fit issue collector missing")
    if "_run_layout_guard" not in app_text:
        issues.append("app runtime layout guard missing")
    if "layout_runtime_latest.json" not in app_text:
        issues.append("runtime layout report output missing")

    # Estimate minimum safe layouts expected by the code. This is a static
    # heuristic, not a screenshot test.
    scenarios = [
        {"name": "tiny_laptop", "width": 900, "height": 620, "expected_sidebar": "icon"},
        {"name": "compact_hd", "width": 1280, "height": 720, "expected_header": "compact"},
        {"name": "large_monitor", "width": 1600, "height": 900, "expected_sidebar": "normal"},
    ]
    settings["scenarios"] = scenarios

    report = {
        "time": datetime.now().isoformat(timespec="seconds"),
        "status": "ok" if not issues else "failed",
        "issues": issues,
        "checks": settings,
    }
    if "--write-report" in sys.argv:
        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(json.dumps(report, ensure_ascii=False, indent=2))
    return 0 if not issues else 1


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