from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any

from iuve_connect_agents.desktop.shared_agent_core.pairing import (
    governance_status_snapshot,
    pairing_status_snapshot,
    platform_storage_root,
)
from iuve_connect_agents.desktop.shared_agent_core.update_governance import evaluate_update_eligibility
from iuve_connect_agents.desktop.shared_agent_core.audit import AuditLogger

APP_NAME = "IuVeConnectAgent"


def app_support_root() -> Path:
    home = Path.home()
    return home / "Library" / "Application Support" / APP_NAME


def runtime_dir(storage_root: Path | None = None) -> Path:
    root = storage_root or platform_storage_root("macos")
    return root / "runtime"


def identity_file(storage_root: Path | None = None) -> Path:
    return runtime_dir(storage_root) / "identity.json"


def runtime_state_file(storage_root: Path | None = None) -> Path:
    return runtime_dir(storage_root) / "runtime_state.json"


def load_or_create_local_identity() -> dict[str, str]:
    pairing = pairing_status_snapshot(platform_storage_root("macos"))
    return {"device_id": pairing["device_id"]}


def load_runtime_state(storage_root: Path | None = None) -> dict[str, Any]:
    path = runtime_state_file(storage_root)
    if not path.exists():
        return {}
    with path.open("r", encoding="utf-8") as handle:
        data = json.load(handle)
    if isinstance(data, dict):
        return data
    return {}


def passive_heartbeat(identity: dict[str, str], trust: dict[str, Any]) -> dict[str, Any]:
    return {
        "ok": True,
        "adapter": "macos",
        "device_id": identity["device_id"],
        "heartbeat": True,
        "trust_state": trust["trust_state"],
        "trust_revoked": trust["trust_revoked"],
        "metadata_only": True,
        "command_channel": False,
        "execution_channel": False,
        "passive_only": True,
    }


def reconnect_backoff(attempt: int) -> float:
    bounded = max(0, min(attempt, 5))
    return min(60.0, 2.0 ** bounded)


def build_local_status(storage_root: Path | None = None) -> dict[str, Any]:
    root = storage_root or platform_storage_root("macos")
    pairing = pairing_status_snapshot(root)
    trust = governance_status_snapshot(root)
    update = evaluate_update_eligibility(
        root,
        platform="macos",
        architecture="amd64",
        expected_channel="internal",
    )
    identity = {"device_id": pairing["device_id"]}
    state = load_runtime_state(root)
    heartbeat = passive_heartbeat(identity, trust)
    # Audit observability
    audit_logger = AuditLogger("macos")
    last_event = audit_logger.get_last_event()
    return {
        "ok": True,
        "adapter": "macos",
        "device_id": pairing["device_id"],
        "pairing_state": pairing["pairing_state"],
        "started": bool(state.get("started", False)),
        "heartbeat": heartbeat,
        "passive_only": pairing["passive_only"],
        "core_version": pairing["core_version"],
        "trust_state": trust["trust_state"],
        "trust_valid": trust["trust_valid"],
        "trust_expired": trust["trust_expired"],
        "trust_revoked": trust["trust_revoked"],
        "update_channel": update.update_channel,
        "update_eligible": update.update_eligible,
        "update_manifest_valid": update.update_manifest_valid,
        "rollback_allowed": update.rollback_allowed,
        "runtime_event_count": audit_logger.get_event_count(),
        "last_audit_event": last_event.timestamp if last_event else None,
        "audit_integrity_ok": audit_logger.get_audit_integrity_ok(),
        "mode": "passive_only",
        "storage": {
            "scope": "local_application_support",
            "identity_file": str(identity_file(root)),
            "runtime_state_file": str(runtime_state_file(root)),
        },
    }


def main() -> int:
    parser = argparse.ArgumentParser(description="IuVe Connect macOS runtime (passive-only)")
    parser.add_argument("--status", action="store_true", help="Return local runtime status as JSON")
    args = parser.parse_args()

    if args.status:
        print(json.dumps(build_local_status(platform_storage_root("macos")), ensure_ascii=True))
        return 0

    print(json.dumps({"ok": False, "error": "unsupported_operation", "allowed": ["--status"]}, ensure_ascii=True))
    return 2


if __name__ == "__main__":
    sys.exit(main())
