"""Reads the agent script bundled into the server image and exposes its
version + sha256 so check-ins can tell agents to self-update.
"""
from __future__ import annotations

import hashlib
import re
from pathlib import Path

_AGENT_PATH = Path("/agent/manage-agent.py")
# Fallback for local dev (not running in container).
if not _AGENT_PATH.exists():
    _AGENT_PATH = Path(__file__).resolve().parent.parent.parent.parent / "agent" / "manage-agent.py"


_state: dict[str, str] = {"version": "", "sha256": ""}


def load() -> None:
    if not _AGENT_PATH.exists():
        return
    raw = _AGENT_PATH.read_bytes()
    _state["sha256"] = hashlib.sha256(raw).hexdigest()
    text = raw.decode("utf-8", errors="replace")
    m = re.search(r'^AGENT_VERSION\s*=\s*["\']([^"\']+)["\']', text, re.MULTILINE)
    _state["version"] = m.group(1) if m else ""


def info() -> dict[str, str]:
    return {"version": _state["version"], "sha256": _state["sha256"]}


def path() -> Path:
    return _AGENT_PATH
