"""Offline maintenance summary for pre-network readiness.

This module only combines local reports.  It never opens sockets, uploads data,
or exposes secrets.  It gives the app one compact health card before future
system-managed networking is enabled.
"""
from __future__ import annotations

from datetime import datetime

from .constants import DATA_DIR
from .storage import save_json

MAINTENANCE_REPORT_PATH = DATA_DIR / "offline_maintenance_latest.json"


def _status_ok(report: dict, default: bool = True) -> bool:
    if not isinstance(report, dict):
        return default
    if "ok" in report:
        return bool(report.get("ok"))
    if "status" in report:
        return str(report.get("status")).upper() in {"OK", "LOCAL_READY", "READY"}
    return default


def build_offline_maintenance_report(
    *,
    app_version: str = "",
    data_integrity: dict | None = None,
    checkpoint_health: dict | None = None,
    sync_integrity: dict | None = None,
    network_readiness: dict | None = None,
    deployment_plan: dict | None = None,
    cutover_dry_run: dict | None = None,
    write_report: bool = True,
) -> dict:
    """Create one local-only maintenance report.

    The report is intentionally summary-only. It contains counts and statuses,
    not document bodies, passwords, tokens, or raw queue payloads.
    """
    data_integrity = data_integrity or {}
    checkpoint_health = checkpoint_health or {}
    sync_integrity = sync_integrity or {}
    network_readiness = network_readiness or {}
    deployment_plan = deployment_plan or {}
    cutover_dry_run = cutover_dry_run or {}

    checks = {
        "data_integrity_ok": _status_ok(data_integrity),
        "checkpoint_health_ok": _status_ok(checkpoint_health),
        "sync_queue_ok": _status_ok(sync_integrity),
        "network_local_or_ready": str(network_readiness.get("status", "local_ready")) in {"local_ready", "ready"},
        "deployment_dry_run_only": deployment_plan.get("will_connect_now") is False,
        "cutover_dry_run_only": cutover_dry_run.get("will_connect") is False,
        "tokens_hidden": deployment_plan.get("token_displayed") is False and network_readiness.get("token_displayed") is False,
    }
    overall_ok = all(bool(value) for value in checks.values())
    report = {
        "time": datetime.now().isoformat(timespec="seconds"),
        "app_version": app_version,
        "status": "OK" if overall_ok else "CHECK",
        "ok": overall_ok,
        "will_connect": False,
        "local_only": True,
        "secret_values_displayed": False,
        "checks": checks,
        "summary": {
            "data_files_checked": int(data_integrity.get("files_checked", 0) or 0),
            "data_unreadable": len(data_integrity.get("unreadable", []) or []),
            "checkpoint_count": int(checkpoint_health.get("checkpoint_count", 0) or 0),
            "latest_checkpoint_age_seconds": checkpoint_health.get("latest_age_seconds"),
            "sync_total": int(sync_integrity.get("total", 0) or 0),
            "sync_pending": int(sync_integrity.get("pending", 0) or 0),
            "sync_failed": int(sync_integrity.get("failed", 0) or 0),
            "network_status": network_readiness.get("status", "local_ready"),
            "deployment_status": deployment_plan.get("status", "local_ready"),
            "cutover_batches": len(cutover_dry_run.get("batches", []) or []),
        },
        "recommendations": [],
    }
    if not checks["data_integrity_ok"]:
        report["recommendations"].append("Run local data integrity repair before enabling managed server mode.")
    if not checks["checkpoint_health_ok"]:
        report["recommendations"].append("Review local checkpoints before future sync.")
    if not checks["sync_queue_ok"]:
        report["recommendations"].append("Repair sync queue before future cutover.")
    if network_readiness.get("status") == "blocked":
        report["recommendations"].append("Keep offline mode until system-managed server config passes policy.")
    if write_report:
        try:
            MAINTENANCE_REPORT_PATH.parent.mkdir(parents=True, exist_ok=True)
            save_json(MAINTENANCE_REPORT_PATH, report)
        except Exception:
            pass
    return report
