"""Persist last heartbeat response extras for GTK console (0.1.21)."""

from __future__ import annotations

import json
import os
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

DEFAULT_STATE_DIR = Path.home() / ".config" / "iuve-connect-agent"
EXTRAS_FILENAME = "heartbeat-extras.json"
SCHEMA_VERSION = "0.1.21"


class HeartbeatExtrasStore:
    def __init__(self, state_dir: Path | None = None) -> None:
        self._path = (state_dir or DEFAULT_STATE_DIR).expanduser() / EXTRAS_FILENAME

    @property
    def path(self) -> Path:
        return self._path

    def save_response(self, response: dict[str, Any]) -> None:
        payload = {
            "schema_version": SCHEMA_VERSION,
            "updated_at": datetime.now(timezone.utc).isoformat(),
            "suggested_actions": list(response.get("suggested_actions") or []),
            "active_session_sync": dict(response.get("active_session_sync") or {}),
        }
        self._path.parent.mkdir(parents=True, exist_ok=True)
        self._path.write_text(json.dumps(payload, ensure_ascii=True, indent=2, sort_keys=True), encoding="utf-8")
        try:
            os.chmod(self._path, 0o600)
        except OSError:
            pass

    def read(self) -> dict[str, Any]:
        if not self._path.exists():
            return {"suggested_actions": [], "active_session_sync": {}}
        try:
            data = json.loads(self._path.read_text(encoding="utf-8"))
            if isinstance(data, dict):
                return data
        except Exception:
            pass
        return {"suggested_actions": [], "active_session_sync": {}}

    def suggested_actions(self) -> list[dict[str, Any]]:
        raw = self.read().get("suggested_actions") or []
        return [dict(item) for item in raw if isinstance(item, dict)]
