"""Check that NexaOffice server networking is system-managed, not user-manual.

Run from project root:
  python tools/system_server_config_check.py --write-report
"""
from __future__ import annotations

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

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


def main() -> int:
    errors: list[str] = []
    required_files = [
        "core/system_server_config.py",
        "server_config.template.json",
        "server/main.py",
        "server/requirements-server.txt",
        "docs/SERVER_DEPLOYMENT_CN.md",
    ]
    for name in required_files:
        if not (ROOT / name).exists():
            errors.append(f"{name} missing")

    app_text = (ROOT / "app.py").read_text(encoding="utf-8", errors="ignore")
    for marker in [
        "apply_system_server_config(self.user_settings)",
        "_system_network_bootstrap",
        "managed_by_system",
        "user_configurable",
        "auto_connect",
    ]:
        if marker not in app_text:
            errors.append(f"app.py missing system networking marker: {marker}")

    settings_text = (ROOT / "pages" / "settings_page.py").read_text(encoding="utf-8", errors="ignore")
    for marker in [
        "server_sync_system_managed",
        "server_user_configurable",
        "server_sync_user_locked",
        "server_sync_open_template",
        "server_sync_open_guide",
    ]:
        if marker not in settings_text:
            errors.append(f"settings_page.py missing locked system connection UI marker: {marker}")

    try:
        template = json.loads((ROOT / "server_config.template.json").read_text(encoding="utf-8"))
        cfg = template.get("server_sync", {})
        if not cfg.get("enabled") or cfg.get("offline_mode"):
            errors.append("server_config.template.json should show enabled system online deployment example")
        if "base_url" not in cfg or "auto_connect" not in cfg:
            errors.append("server_config.template.json missing base_url/auto_connect")
        if cfg.get("deployment_mode") != "server":
            errors.append("server_config.template.json should declare deployment_mode=server")
    except Exception as exc:
        errors.append(f"server_config.template.json invalid: {exc}")

    for lang_name in ("zh_CN", "en_US", "id_ID"):
        try:
            lang = json.loads((ROOT / "lang" / f"{lang_name}.json").read_text(encoding="utf-8"))
            for key in [
                "server_sync_system_managed",
                "server_sync_user_locked",
                "server_sync_config_source",
                "server_sync_runtime_online",
                "server_sync_auto_connect_on",
                "server_sync_open_template",
                "server_sync_open_guide",
                "server_sync_not_configured",
            ]:
                if key not in lang:
                    errors.append(f"{lang_name} missing {key}")
        except Exception as exc:
            errors.append(f"{lang_name} could not be read: {exc}")

    report = {
        "checked_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "status": "OK" if not errors else "FAILED",
        "errors": errors,
        "notes": [
            "Networking is controlled by system deployment config instead of normal user manual switches.",
            "Auto connection only runs when a deployment config explicitly enables it.",
            "No token should be displayed in UI or diagnostic text.",
        ],
    }
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--write-report", action="store_true")
    args = parser.parse_args()
    if args.write_report:
        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("NexaOffice System Server Config Check")
    print(f"- Status: {report['status']}")
    for err in errors:
        print("  ", err)
    if args.write_report:
        print(f"- Report: {REPORT_PATH.relative_to(ROOT)}")
    return 0 if not errors else 1


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