"""Autopilot state directory resolution."""

from __future__ import annotations

import os
from pathlib import Path

from .policy import AutonomyPolicy


def _expand_path(path_value: str, state_dir: str | None = None) -> str:
    value = path_value
    if state_dir:
        value = value.replace("${state_dir}", state_dir)
    value = os.path.expandvars(value)
    value = os.path.expanduser(value)
    return value


def resolve_state_dir(policy: AutonomyPolicy, *, create: bool = True) -> Path:
    override = os.getenv("G_GREMLIN_STATE_DIR")
    base_raw = override.strip() if override else policy.defaults.state_dir
    base_expanded = _expand_path(base_raw)
    base_path = Path(base_expanded).resolve()

    receipts_dir = _expand_path(policy.defaults.receipt_dir, str(base_path))
    receipts_path = Path(receipts_dir).resolve()

    if create:
        (base_path / "db").mkdir(parents=True, exist_ok=True)
        (base_path / "policy_overrides.d").mkdir(parents=True, exist_ok=True)
        (base_path / "locks").mkdir(parents=True, exist_ok=True)
        receipts_path.mkdir(parents=True, exist_ok=True)

    return base_path


__all__ = ["resolve_state_dir"]
