"""NexaOffice performance guard regression check.
Run from project root: python tools/performance_guard_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


def _app_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:
    errors = []
    app_py = (ROOT / "app.py").read_text(encoding="utf-8", errors="ignore")
    storage_py = (ROOT / "core" / "storage.py").read_text(encoding="utf-8", errors="ignore")
    network_py = (ROOT / "core" / "network.py").read_text(encoding="utf-8", errors="ignore")
    sync_queue_py = (ROOT / "core" / "sync_queue.py").read_text(encoding="utf-8", errors="ignore")

    required_markers = {
        "on_demand layout guard": '"layout_guard_mode": "on_demand"',
        "resize debounce setting": '"resize_debounce_ms"',
        "resize min delta setting": '"resize_min_delta"',
        "scroll cache setting": '"scroll_target_cache_ms"',
        "scroll cache invalidator": "def _invalidate_scroll_widget_cache",
        "scroll cache storage": "_scroll_widget_cache_at",
        "responsive duplicate skip": "_last_responsive_signature",
        "deferred page responsive pass": "Do not synchronously run the full responsive pass while switching",
        "last wheel target cache": "_last_scroll_target_y",
        "network test single flight": "_network_test_in_progress",
    }
    for label, marker in required_markers.items():
        if marker not in app_py:
            errors.append(f"Missing performance guard marker: {label}")

    cross_file_markers = {
        "single scoped workspace load": (storage_py, "scoped = load_scoped_workspace_data()"),
        "cached link metadata": (storage_py, "_LINK_METADATA_CACHE"),
        "settings mode mtime cache": (storage_py, "_SETTINGS_MODE_CACHE"),
        "sync queue skip unchanged payload": (sync_queue_py, 'existing.get("payload") == compacted_payload'),
        "network health cache": (network_py, "_HEALTH_CACHE"),
        "network health cache ttl": (network_py, 'ttl = float(getattr(self.config, "health_cache_ttl_ok", 45.0)) if cached.get("ok") else float(getattr(self.config, "health_cache_ttl_fail", 12.0))'),
    }
    for label, (source, marker) in cross_file_markers.items():
        if marker not in source:
            errors.append(f"Missing performance/network marker: {label}")

    if 'root.after(180 if not getattr(self, "login_screen_active"' in app_py:
        errors.append("Restore watcher still polls at the old 180ms interval")
    if "abs(width - last_w) < 8" in app_py or "abs(height - last_h) < 8" in app_py:
        errors.append("Root Configure jitter guard still uses the old 8px threshold")
    if "self._apply_responsive_layout()\n            self._schedule_layout_guard" in app_py:
        errors.append("Page switch still applies responsive layout synchronously")

    report = {
        "time": datetime.now().isoformat(timespec="seconds"),
        "version": _app_version(),
        "status": "ok" if not errors else "failed",
        "checks": {
            "layout_guard_default_on_demand": '"layout_guard_mode": "on_demand"' in app_py,
            "resize_debounce_present": '"resize_debounce_ms"' in app_py,
            "scroll_target_cache_present": "_scroll_widget_cache_at" in app_py,
            "last_wheel_target_cache": "_last_scroll_target_y" in app_py,
            "single_scoped_workspace_load": "scoped = load_scoped_workspace_data()" in storage_py,
            "settings_mode_mtime_cache": "_SETTINGS_MODE_CACHE" in storage_py,
            "sync_queue_skip_unchanged_payload": 'existing.get("payload") == compacted_payload' in sync_queue_py,
            "network_health_cache": "_HEALTH_CACHE" in network_py,
            "network_test_single_flight": "_network_test_in_progress" in app_py,
            "restore_watcher_not_180ms": 'root.after(180 if not getattr(self, "login_screen_active"' not in app_py,
            "page_switch_responsive_deferred": "Do not synchronously run the full responsive pass while switching" in app_py,
        },
        "errors": errors,
    }
    if "--write-report" in sys.argv:
        out = ROOT / "data" / "performance_guard_latest.json"
        out.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
    if errors:
        for err in errors:
            print(err)
        return 1
    print("Performance guard check OK")
    return 0


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