from __future__ import annotations

import json
import sys
from pathlib import Path
from typing import Any, Optional

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

APPDATA_ROOT = platform_storage_root("windows")
RUNTIME_STATE_FILE = APPDATA_ROOT / "runtime_state.json"


def load_or_create_local_identity() -> dict:
    pairing = pairing_status_snapshot(APPDATA_ROOT)
    return {"device_id": pairing["device_id"]}


def save_runtime_state(state: dict, storage_root: Path | None = None) -> None:
    root = storage_root or APPDATA_ROOT
    runtime_state_file = root / "runtime_state.json"
    root.mkdir(parents=True, exist_ok=True)
    with runtime_state_file.open("w", encoding="utf-8") as f:
        json.dump(state, f)


def load_runtime_state(storage_root: Path | None = None) -> Optional[dict]:
    root = storage_root or APPDATA_ROOT
    runtime_state_file = root / "runtime_state.json"
    if runtime_state_file.exists():
        with runtime_state_file.open("r", encoding="utf-8") as f:
            return json.load(f)
    return None


def passive_heartbeat(identity: dict, trust: dict) -> dict:
    # Only status metadata, no control-plane actions
    return {
        "ok": True,
        "adapter": "windows",
        "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 build_local_status(storage_root: Path | None = None) -> dict[str, Any]:
    root = storage_root or APPDATA_ROOT
    pairing = pairing_status_snapshot(root)
    state = load_runtime_state(root) or {}
    trust = governance_status_snapshot(root)
    heartbeat = passive_heartbeat({"device_id": pairing["device_id"]}, trust)
    update = evaluate_update_eligibility(
        root,
        platform="windows",
        architecture="amd64",
        expected_channel="internal",
    )
    audit_logger = AuditLogger("windows")
    last_event = audit_logger.get_last_event()
    return {
        "ok": True,
        "adapter": "windows",
        "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_appdata",
            "runtime_state_file": str(root / "runtime_state.json"),
        },
    }


# --- PHASE 10A: Passive-only, JSON-only, no OS/process/command control ---
def main():
    import argparse
    parser = argparse.ArgumentParser(description="IuVe Connect Windows Agent Runtime (passive-only)")
    parser.add_argument("--status", action="store_true", help="Output local agent status as JSON")
    args = parser.parse_args()

    if args.status:
        print(json.dumps(build_local_status(APPDATA_ROOT), ensure_ascii=True))
        return
    # If called without --status, output safe error
    print(json.dumps({"ok": False, "error": "unsupported_operation", "allowed": ["--status"]}))
    sys.exit(2)

if __name__ == "__main__":
    main()
