"""Guard NexaOffice server deployment readiness contract.

This is a dry-run/static check. It does not connect to a server.
"""
from __future__ import annotations

import json
from datetime import datetime
from pathlib import Path

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


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

    for marker in [
        '"POST /api/bootstrap"',
        '"POST /api/sync/batch"',
        '"scope_isolation_required": True',
        '"token_displayed": False',
        '"required_headers"',
    ]:
        if marker not in network:
            issues.append(f"core/network.py missing deployment contract marker: {marker}")

    for marker in [
        '@app.post("/api/bootstrap")',
        '@app.post("/api/sync/batch")',
        'class BootstrapRequest',
        'class SyncBatchEnvelope',
        'supported_scopes',
        'token_displayed',
        '_scope_value',
    ]:
        if marker not in server:
            issues.append(f"server/main.py missing endpoint marker: {marker}")

    for marker in [
        'scope_sync_context',
        'is_item_visible_in_current_scope',
        'visible_todo_items',
        'chat_scope"] = "enterprise"',
        'chat_scope"] = "personal"',
    ]:
        if marker not in app:
            issues.append(f"app.py missing post-login isolation marker: {marker}")

    for marker in [
        'POST /api/bootstrap',
        'POST /api/sync/batch',
        'Personal 模式不能读取 enterprise 数据',
        'Enterprise 模式不能读取 personal 数据',
        'cutover dry-run',
    ]:
        if marker not in docs:
            issues.append(f"SERVER_DEPLOYMENT_CN.md missing deployment note: {marker}")

    try:
        template = json.loads((ROOT / "server_config.template.json").read_text(encoding="utf-8"))
        cfg = template.get("server_sync", {})
        if cfg.get("client_contract") != "v2026.06.20.80-scope-isolated":
            issues.append("server_config.template.json missing v80 client_contract")
        if cfg.get("retry_count", 0) < 2:
            issues.append("server_config.template.json retry_count should be >= 2")
        if not cfg.get("required_scopes"):
            issues.append("server_config.template.json missing required_scopes")
    except Exception as exc:
        issues.append(f"server_config.template.json invalid: {exc}")

    payload = {
        "time": datetime.now().isoformat(timespec="seconds"),
        "status": "OK" if not issues else "FAILED",
        "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("Server deployment readiness guard", payload["status"])
    for issue in issues:
        print("-", issue)
    return 0 if not issues else 1


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