"""Guard Profile dialog UX fixes.

Normal users should not see duplicate exit-like buttons in Profile.  The Profile
dialog and contact-card editor must use forced centering and scrollable editors.
"""
from pathlib import Path
import json
from datetime import datetime

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

app_py = (ROOT / "app.py").read_text(encoding="utf-8", errors="ignore")
profile_start = app_py.find("def show_profile")
profile_end = app_py.find("def refresh_user_state", profile_start)
profile = app_py[profile_start:profile_end] if profile_start != -1 and profile_end != -1 else ""
edit_start = app_py.find("def edit_contact_card_dialog")
edit_end = app_py.find("def show_profile", edit_start)
edit = app_py[edit_start:edit_end] if edit_start != -1 and edit_end != -1 else ""

checks = {
    "profile_has_force_center": "force_center_profile" in profile and "win.deiconify()" in profile and "win.withdraw()" in profile,
    "profile_single_logout_button": profile.count("profile_logout_btn") == 1 and 'self.t("logout_btn")' not in profile,
    "profile_uses_logout_not_app_quit": "profile_logout_btn" in profile and "logout_to_login()" in profile and "self.exit_app()" not in profile,
    "profile_button_grid": "button_grid.grid_columnconfigure" in profile,
    "contact_editor_scrollable": "scroll_wrap" in edit and "canvas.yview_scroll" in edit,
    "contact_editor_forced_center": "force_center" in edit and "win.withdraw()" in edit and "win.deiconify()" in edit,
    "contact_editor_no_tutup_button": 'self.t("profile_close")' not in edit,
}
issues = [name for name, ok in checks.items() if not ok]
payload = {
    "time": datetime.now().isoformat(timespec="seconds"),
    "status": "OK" if not issues else "FAILED",
    "checks": checks,
    "issues": issues,
}
REPORT.parent.mkdir(parents=True, exist_ok=True)
REPORT.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
print("Profile dialog guard", payload["status"])
if issues:
    for issue in issues:
        print("-", issue)
raise SystemExit(0 if not issues else 1)
