"""Network readiness guard for pre-server NexaOffice releases.

This check is offline-only. It verifies that future online mode is still:
- system-managed, not normal-user manual config;
- HTTPS or localhost-only HTTP;
- token-safe in reports/logs;
- using a bounded, repairable sync queue.
"""
from __future__ import annotations

import json
from pathlib import Path
import sys

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


def main() -> int:
    errors: list[str] = []
    network_py = (ROOT / "core" / "network.py").read_text(encoding="utf-8", errors="ignore")
    sync_py = (ROOT / "core" / "sync_queue.py").read_text(encoding="utf-8", errors="ignore")
    app_py = (ROOT / "app.py").read_text(encoding="utf-8", errors="ignore")
    settings_py = (ROOT / "pages" / "settings_page.py").read_text(encoding="utf-8", errors="ignore")

    for marker in [
        "def network_readiness_report",
        "NETWORK_PREFLIGHT_PATH",
        '"token_displayed": False',
        '"auto_connect_guarded"',
        '"no_user_manual_server_form"',
        "validate_base_url_policy",
        "is_loopback_host",
        "retry_backoff_base",
        "health_cache_ttl_ok",
        "health_cache_ttl_fail",
    ]:
        if marker not in network_py:
            errors.append(f"core/network.py missing marker: {marker}")

    for marker in [
        "SYNC_QUEUE_SECRET_KEYS",
        "def _redact_payload",
        "def repair_sync_queue",
        "last_repaired_at",
        "SYNC_QUEUE_MAX_ITEMS",
    ]:
        if marker not in sync_py:
            errors.append(f"core/sync_queue.py missing marker: {marker}")

    for marker in [
        "network_readiness_report",
        "repair_sync_queue_local",
        "get_network_readiness_report",
        "readiness.get(\"status\") == \"blocked\"",
    ]:
        if marker not in app_py:
            errors.append(f"app.py missing network readiness marker: {marker}")

    for marker in [
        "server_sync_readiness_title",
        "server_sync_repair_queue",
        "server_readiness",
        "repair_sync_queue",
    ]:
        if marker not in settings_py:
            errors.append(f"settings_page.py missing readiness UI marker: {marker}")

    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_readiness_title",
                "server_sync_readiness_ready",
                "server_sync_readiness_local",
                "server_sync_readiness_blocked",
                "server_sync_readiness_token_safe",
                "server_sync_repair_queue",
                "server_sync_queue_repaired",
            ]:
                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}")

    payload = {
        "status": "OK" if not errors else "FAILED",
        "errors": errors,
        "notes": [
            "This guard does not contact a server.",
            "Normal users should not manually configure server URLs or tokens.",
            "Readiness reports must never include API token values.",
            "HTTP remains restricted to localhost development only.",
        ],
    }
    REPORT_PATH.parent.mkdir(parents=True, exist_ok=True)
    REPORT_PATH.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
    print("Network readiness guard", payload["status"])
    for err in errors:
        print("-", err)
    return 0 if not errors else 1


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