"""Persist PC companion agents outside state.json so the LAN agent cannot wipe them."""
from __future__ import annotations

import json
import time
from pathlib import Path
from typing import Any

DATA = Path("/var/lib/atlas-cyber-protect")
AGENTS_FILE = DATA / "companion-agents.json"


def load_agents() -> dict[str, dict[str, Any]]:
    try:
        if AGENTS_FILE.is_file():
            raw = json.loads(AGENTS_FILE.read_text(encoding="utf-8"))
            if isinstance(raw, dict):
                return {str(k): v for k, v in raw.items() if isinstance(v, dict)}
    except Exception:
        pass
    # Migrate from state.json once
    try:
        st_path = DATA / "state.json"
        if st_path.is_file():
            st = json.loads(st_path.read_text(encoding="utf-8"))
            agents = st.get("companion_agents") or {}
            if isinstance(agents, dict) and agents:
                save_agents(agents)
                return {str(k): v for k, v in agents.items() if isinstance(v, dict)}
    except Exception:
        pass
    return {}


def save_agents(agents: dict[str, dict[str, Any]]) -> None:
    DATA.mkdir(parents=True, exist_ok=True)
    AGENTS_FILE.write_text(json.dumps(agents, indent=2) + "\n", encoding="utf-8")
    # Mirror into state for older UI/tools (best-effort)
    try:
        st_path = DATA / "state.json"
        st: dict[str, Any] = {}
        if st_path.is_file():
            st = json.loads(st_path.read_text(encoding="utf-8"))
            if not isinstance(st, dict):
                st = {}
        st["companion_agents"] = agents
        st_path.write_text(json.dumps(st), encoding="utf-8")
    except Exception:
        pass


def upsert_agent(agent_id: str, row: dict[str, Any]) -> dict[str, Any]:
    agents = load_agents()
    agents[agent_id] = row
    save_agents(agents)
    return row


def get_agent(agent_id: str) -> dict[str, Any] | None:
    return load_agents().get(agent_id)


def touch_activity(plain: str) -> None:
    try:
        st_path = DATA / "state.json"
        st: dict[str, Any] = {}
        if st_path.is_file():
            st = json.loads(st_path.read_text(encoding="utf-8")) or {}
        act = list(st.get("activity") or [])
        act.insert(0, {"ts": time.time(), "plain": plain[:400]})
        st["activity"] = act[:40]
        st_path.write_text(json.dumps(st), encoding="utf-8")
    except Exception:
        pass
