"""NexaOffice login adaptation regression check.

Run from project root:
    python tools/login_adaptation_check.py --write-report

This guards the login screen from returning to a fixed 900x620 canvas or
mixed widget/canvas scaling, which caused some PCs to show oversized controls
and other PCs to show tiny text.
"""
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" / "login_adaptation_latest.json"


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


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

    required_markers = {
        "real viewport width": "view_w = int(canvas.winfo_width()",
        "real viewport height": "view_h = int(canvas.winfo_height()",
        "compact login mode": "compact_login = cw < 1180 or ch < 720",
        "tiny login mode": "tiny_login = cw < 900 or ch < 610",
        "login text scale clamp": "text_scale = max(0.96, min(1.20, s))",
        "login widget font sync": "def configure_login_widget_fonts():",
        "compact login branch": "if compact_login:",
        "hide dashboard preview in compact": "Compact / split-screen login: hide the marketing preview",
        "no mixed widget sizes": "for chip in chip_widgets",
        "desktop login size lock": "target_shell_w = min(2100, cw * 0.996)",
        "redraw fingerprint guard": "draw_state = {\"sig\": None, \"when\": 0.0}",
        "login background animation": "pulse_login_background",
    }
    for label, marker in required_markers.items():
        if marker not in app:
            issues.append(f"Missing login adaptation marker: {label}")

    banned_fragments = {
        "fake min canvas width": "cw = max(canvas.winfo_width(), 900)",
        "fake min canvas height": "ch = max(canvas.winfo_height(), 620)",
        "old reference-only scale": "s = min(cw / 1672.0, ch / 941.0)",
    }
    for label, marker in banned_fragments.items():
        if marker in app:
            issues.append(f"Old login adaptation code still present: {label}")

    report = {
        "time": datetime.now().isoformat(timespec="seconds"),
        "version": _version(),
        "status": "OK" if not issues else "FAILED",
        "checks": {
            "uses_real_canvas_viewport": "view_w = int(canvas.winfo_width()" in app,
            "has_compact_single_card_mode": "if compact_login:" in app,
            "syncs_tk_widget_fonts": "def configure_login_widget_fonts():" in app,
            "has_large_desktop_login_shell": "target_shell_w = min(2100, cw * 0.996)" in app,
            "avoids_fake_900x620_floor": "cw = max(canvas.winfo_width(), 900)" not in app,
            "avoids_old_1672x941_only_scale": "s = min(cw / 1672.0, ch / 941.0)" not in app,
        },
        "issues": issues,
    }
    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())
