"""Auto governance snapshot reader with graceful fallbacks."""

from __future__ import annotations

import json
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Optional

import config_manager


def _candidate_logs_dirs(app_dir: Optional[Path]) -> list[Path]:
    candidates: list[Path] = []
    if app_dir is not None:
        root = Path(app_dir)
        candidates.append(root if root.name == "logs" else root / "logs")
    try:
        candidates.append(config_manager.get_logs_dir())
    except Exception:
        pass
    if sys.platform == "darwin":
        candidates.append(Path.home() / "Library/Application Support/LobsterQuant/logs")

    deduped: list[Path] = []
    seen = set()
    for candidate in candidates:
        key = str(candidate.expanduser())
        if key in seen:
            continue
        seen.add(key)
        deduped.append(candidate.expanduser())
    return deduped


def _artifact_freshness(logs_dir: Path) -> float:
    freshest = 0.0
    for name in (
        "auto_governance_status_latest.json",
        "autonomy_loop_latest.json",
        "live_learner_summary_latest.json",
        "shadow_learner_summary_latest.json",
        "hermes_governance_brief.json",
    ):
        path = logs_dir / name
        try:
            if path.exists():
                freshest = max(freshest, float(path.stat().st_mtime))
        except Exception:
            continue
    return freshest


def _logs_dir(app_dir: Optional[Path]) -> Path:
    candidates = _candidate_logs_dirs(app_dir)
    if not candidates:
        return config_manager.get_logs_dir()
    best = max(candidates, key=_artifact_freshness)
    if _artifact_freshness(best) > 0:
        return best
    return candidates[0]


def _read_json(path: Path) -> Dict[str, Any]:
    try:
        payload = json.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return {}
    return payload if isinstance(payload, dict) else {}


def _file_timestamp(path: Path) -> str:
    try:
        return datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc).isoformat()
    except Exception:
        return ""


def _default_snapshot() -> Dict[str, Any]:
    return {
        "available": False,
        "phase": "trial",
        "status": "NOOP",
        "enabled": True,
        "currentMode": "shadow",
        "nextMode": "",
        "lastAction": "NOOP",
        "lastReason": "",
        "next_action": "NONE",
        "recentActions": [],
        "timestamp": "",
    }


def _normalize_governance_payload(payload: Dict[str, Any], *, timestamp: str) -> Dict[str, Any]:
    snapshot = _default_snapshot()
    snapshot.update(payload)
    snapshot["available"] = True
    snapshot["status"] = str(
        payload.get("status", payload.get("auto_governance_status", payload.get("last_action", "NOOP"))) or "NOOP"
    )
    snapshot["currentMode"] = str(
        payload.get("currentMode", payload.get("current_mode", payload.get("last_mode", "shadow"))) or "shadow"
    )
    snapshot["nextMode"] = str(payload.get("nextMode", payload.get("next_mode", "")) or "")
    snapshot["lastAction"] = str(
        payload.get("lastAction", payload.get("last_action", payload.get("action", snapshot["status"]))) or snapshot["status"]
    )
    snapshot["lastReason"] = str(
        payload.get("lastReason", payload.get("last_reason", payload.get("reason", ""))) or ""
    )
    snapshot["next_action"] = str(payload.get("next_action", payload.get("nextAction", snapshot["lastAction"])) or snapshot["lastAction"])
    snapshot["timestamp"] = str(
        payload.get("timestamp", payload.get("generated_at", payload.get("ts", timestamp))) or timestamp
    )
    return snapshot


def _build_fallback_snapshot(logs_dir: Path) -> Dict[str, Any]:
    snapshot = _default_snapshot()
    live_learner = _read_json(logs_dir / "live_learner_summary_latest.json")
    shadow_learner = _read_json(logs_dir / "shadow_learner_summary_latest.json")
    autonomy_loop = _read_json(logs_dir / "autonomy_loop_latest.json")
    hermes_brief = _read_json(logs_dir / "hermes_governance_brief.json")

    source_payload = autonomy_loop or live_learner or hermes_brief or shadow_learner
    if not source_payload:
        return snapshot

    ts = ""
    for candidate in (
        logs_dir / "autonomy_loop_latest.json",
        logs_dir / "live_learner_summary_latest.json",
        logs_dir / "hermes_governance_brief.json",
        logs_dir / "shadow_learner_summary_latest.json",
    ):
        if candidate.exists():
            ts = _file_timestamp(candidate)
            if ts:
                break

    snapshot["available"] = True
    snapshot["status"] = str(
        source_payload.get("status")
        or source_payload.get("auto_governance_status")
        or source_payload.get("governance_action")
        or "NOOP"
    )
    snapshot["currentMode"] = str(
        live_learner.get("currentMode")
        or source_payload.get("currentMode")
        or source_payload.get("current_mode")
        or "shadow"
    )
    snapshot["nextMode"] = str(source_payload.get("nextMode", source_payload.get("next_mode", "")) or "")
    snapshot["lastAction"] = str(
        source_payload.get("lastAction")
        or source_payload.get("last_action")
        or source_payload.get("governance_action")
        or snapshot["status"]
    )
    snapshot["lastReason"] = str(
        source_payload.get("lastReason")
        or source_payload.get("last_reason")
        or source_payload.get("governance_reason")
        or source_payload.get("selection_reason")
        or ""
    )
    snapshot["next_action"] = str(
        autonomy_loop.get("next_action")
        or source_payload.get("next_action")
        or snapshot["lastAction"]
    )
    snapshot["recentActions"] = autonomy_loop.get("recentActions", source_payload.get("recentSelections", []))
    snapshot["timestamp"] = str(
        source_payload.get("timestamp")
        or source_payload.get("generated_at")
        or source_payload.get("ts")
        or ts
    )
    return snapshot


def run_auto_governance_cycle(
    app_dir: Optional[Path] = None,
    tenant_id: str = "default",
    *,
    source: str = "manual",
) -> Dict[str, Any]:
    """Return the latest governance snapshot as a best-effort governance tick."""
    snapshot = load_auto_governance_snapshot(app_dir)
    snapshot["tenant_id"] = tenant_id or "default"
    snapshot["source"] = source
    return snapshot


def load_auto_governance_snapshot(app_dir: Optional[Path] = None) -> Dict[str, Any]:
    """Load the latest auto-governance snapshot for dashboard and status APIs."""
    logs_dir = _logs_dir(app_dir)
    status_file = logs_dir / "auto_governance_status_latest.json"
    if status_file.exists():
        payload = _read_json(status_file)
        if payload:
            return _normalize_governance_payload(payload, timestamp=_file_timestamp(status_file))
    return _build_fallback_snapshot(logs_dir)
