"""Local CLI state and control signal management."""

from __future__ import annotations

import json
import os
from pathlib import Path
from typing import Any


def _default_state_dir() -> Path:
    env_dir = os.getenv("CLIPROOM_STATE_DIR")
    if env_dir:
        return Path(env_dir)
    return Path.cwd() / ".cliproom"


class LocalCLIState:
    """Stores local runtime status for status/leave commands."""

    def __init__(self, state_dir: Path | None = None) -> None:
        self.state_dir = state_dir or _default_state_dir()
        self.state_file = self.state_dir / "client_state.json"
        self.leave_file = self.state_dir / "leave.request"
        self.server_state_file = self.state_dir / "server_state.json"
        self.server_stop_file = self.state_dir / "server_stop.request"

    def write_state(self, payload: dict[str, Any]) -> None:
        self.state_dir.mkdir(parents=True, exist_ok=True)
        self.state_file.write_text(json.dumps(payload, indent=2), encoding="utf-8")

    def read_state(self) -> dict[str, Any] | None:
        if not self.state_file.exists():
            return None
        try:
            return json.loads(self.state_file.read_text(encoding="utf-8"))
        except Exception:
            return None

    def set_leave_requested(self) -> None:
        self.state_dir.mkdir(parents=True, exist_ok=True)
        self.leave_file.write_text("1", encoding="utf-8")

    def clear_leave_requested(self) -> None:
        if self.leave_file.exists():
            self.leave_file.unlink()

    def is_leave_requested(self) -> bool:
        return self.leave_file.exists()

    def write_server_state(self, payload: dict[str, Any]) -> None:
        self.state_dir.mkdir(parents=True, exist_ok=True)
        self.server_state_file.write_text(json.dumps(payload, indent=2), encoding="utf-8")

    def read_server_state(self) -> dict[str, Any] | None:
        if not self.server_state_file.exists():
            return None
        try:
            return json.loads(self.server_state_file.read_text(encoding="utf-8"))
        except Exception:
            return None

    def set_server_stop_requested(self) -> None:
        self.state_dir.mkdir(parents=True, exist_ok=True)
        self.server_stop_file.write_text("1", encoding="utf-8")

    def clear_server_stop_requested(self) -> None:
        if self.server_stop_file.exists():
            self.server_stop_file.unlink()

    def is_server_stop_requested(self) -> bool:
        return self.server_stop_file.exists()


def is_pid_running(pid: int) -> bool:
    """Return whether pid appears alive."""
    if pid <= 0:
        return False
    try:
        os.kill(pid, 0)
    except OSError:
        return False
    return True
