"""Persistent session state for the terminal client."""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

from clients.terminal.config import settings


class StateManager:
    """Read/write ~/.navi_code/state.json."""

    def __init__(self, state_dir: Path | None = None) -> None:
        self.state_dir = state_dir or settings.state_dir
        self.state_file = self.state_dir / "state.json"

    def _ensure_dir(self) -> None:
        self.state_dir.mkdir(parents=True, exist_ok=True)

    def load(self) -> dict[str, Any]:
        if not self.state_file.exists():
            return {}
        try:
            with self.state_file.open("r", encoding="utf-8") as f:
                return json.load(f)
        except (json.JSONDecodeError, OSError):
            return {}

    def save(self, data: dict[str, Any]) -> None:
        self._ensure_dir()
        with self.state_file.open("w", encoding="utf-8") as f:
            json.dump(data, f, indent=2, ensure_ascii=False)

    def get_session_id(self) -> str | None:
        return self.load().get("session_id")

    def set_session_id(self, session_id: str) -> None:
        state = self.load()
        state["session_id"] = session_id
        self.save(state)

    def clear_session_id(self) -> None:
        state = self.load()
        state.pop("session_id", None)
        self.save(state)
