from __future__ import annotations

import subprocess
import sys
from pathlib import Path
from typing import Any

from .process import run_cli_hidden


GAME_EXE_NAME = "AssettoCorsaEVO.exe"


def game_exe_path(game_root: str | Path) -> Path:
    root = Path(game_root).expanduser().resolve()
    exe = root / GAME_EXE_NAME
    if not exe.is_file():
        raise FileNotFoundError(f"AC EVO executable not found: {exe}")
    return exe


def is_game_running() -> bool:
    if not sys.platform.startswith("win"):
        return False
    try:
        result = run_cli_hidden(
            ["tasklist", "/FI", f"IMAGENAME eq {GAME_EXE_NAME}", "/FO", "CSV", "/NH"],
            capture_output=True,
            text=True,
            encoding="utf-8",
            errors="replace",
            check=False,
        )
    except Exception:
        return False
    return GAME_EXE_NAME.lower() in str(result.stdout or "").lower()


def start_game(game_root: str | Path) -> dict[str, Any]:
    exe = game_exe_path(game_root)
    if is_game_running():
        return {"started": False, "alreadyRunning": True, "exe": str(exe), "pid": None}
    process = subprocess.Popen([str(exe)], cwd=str(exe.parent))
    return {"started": True, "alreadyRunning": False, "exe": str(exe), "pid": process.pid}
