from __future__ import annotations

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


def repo_root() -> Path:
    env_root = os.environ.get("TOTALLY_SPIES_REPO_ROOT")
    if env_root:
        return Path(env_root).resolve()
    try:
        out = subprocess.check_output(["git", "rev-parse", "--show-toplevel"], text=True).strip()
        if out:
            return Path(out).resolve()
    except Exception:
        pass
    return Path.cwd().resolve()


def state_dir() -> Path:
    env_state = os.environ.get("TOTALLY_SPIES_DEVENV_STATE_ROOT")
    if env_state:
        return Path(env_state).resolve()
    return repo_root() / ".devenv" / "state"


STATE_DIR = state_dir()
BUILDER_HOST_STATE_FILE = Path(os.environ.get("TOTALLY_SPIES_BUILDER_HOST_STATE_FILE", STATE_DIR / "builder-host.json"))
BUILDER_RESCUE_FACTS_FILE = Path(os.environ.get("TOTALLY_SPIES_BUILDER_RESCUE_FACTS_FILE", STATE_DIR / "builder-rescue-facts.json"))
BUILDER_ROOTFS_PLAN_FILE = Path(os.environ.get("TOTALLY_SPIES_BUILDER_ROOTFS_PLAN_FILE", STATE_DIR / "builder-rootfs-plan.json"))
BUILDER_REMOTE_CONF_FILE = Path(os.environ.get("TOTALLY_SPIES_BUILDER_REMOTE_CONF_FILE", STATE_DIR / "builder-remote.conf"))
LEGACY_STATE_FILES = {
    "builder-host": STATE_DIR / "hetzner-market-builder.json",
    "builder-rescue-facts": STATE_DIR / "hetzner-rescue-facts.json",
    "builder-rootfs-plan": STATE_DIR / "hetzner-layout-plan.json",
    "builder-remote-conf": STATE_DIR / "builder.nix.conf",
}


def load_json_file(path: Path) -> dict[str, Any]:
    if not path.exists():
        return {}
    text = path.read_text().strip()
    if not text:
        return {}
    payload = json.loads(text)
    return payload if isinstance(payload, dict) else {}


def save_json_file(path: Path, payload: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(payload, indent=2) + "\n")
