from dataclasses import dataclass
import subprocess

from l4d2host.service_control import show_service


@dataclass(slots=True)
class InstanceStatus:
    state: str
    raw_active_state: str
    raw_sub_state: str


def map_active_state(active_state: str) -> str:
    if active_state == "active":
        return "running"
    if active_state in {"inactive", "failed"}:
        return "stopped"
    return "unknown"


def get_instance_status(name: str) -> InstanceStatus:
    try:
        result = show_service(name)
    except (subprocess.CalledProcessError, FileNotFoundError):
        return InstanceStatus(
            state="unknown",
            raw_active_state="unknown",
            raw_sub_state="unknown",
        )

    values: dict[str, str] = {}
    for line in result.stdout.splitlines():
        if "=" not in line:
            continue
        key, value = line.split("=", 1)
        values[key] = value

    active_state = values.get("ActiveState", "unknown")
    sub_state = values.get("SubState", "unknown")

    return InstanceStatus(
        state=map_active_state(active_state),
        raw_active_state=active_state,
        raw_sub_state=sub_state,
    )
