"""Thread-safe agent activity for heartbeat sync to Connect web UI (0.2.2.70)."""

from __future__ import annotations

import threading
from dataclasses import dataclass

_VALID_STATES = frozenset({"idle", "working", "blocked", "error"})

_lock = threading.Lock()
_activity = "idle"
_label = ""


@dataclass(frozen=True)
class AgentActivitySnapshot:
    agent_activity: str = "idle"
    activity_label: str = ""


def _normalize_state(state: str) -> str:
    normalized = str(state or "idle").strip().lower()
    if normalized not in _VALID_STATES:
        return "idle"
    return normalized


def set_agent_activity(state: str, *, label: str = "") -> AgentActivitySnapshot:
    global _activity, _label
    normalized = _normalize_state(state)
    trimmed_label = str(label or "").strip()[:128]
    with _lock:
        _activity = normalized
        _label = trimmed_label if normalized != "idle" else ""
        return AgentActivitySnapshot(agent_activity=_activity, activity_label=_label)


def read_agent_activity() -> AgentActivitySnapshot:
    with _lock:
        return AgentActivitySnapshot(agent_activity=_activity, activity_label=_label)


def read_agent_activity_heartbeat_fields() -> dict[str, str]:
    snap = read_agent_activity()
    fields: dict[str, str] = {"agent_activity": snap.agent_activity}
    if snap.activity_label:
        fields["activity_label"] = snap.activity_label
    return fields
