"""Per-run pi account composition; never alters the machine-wide pi auth link."""
from __future__ import annotations

import os
import shutil
from pathlib import Path
from uuid import uuid4


def _home() -> Path:
    return Path(os.environ.get("HOME", str(Path.home()))).expanduser()


def source_agent_dir() -> Path:
    return _home() / ".pi" / "agent"


def registry_root() -> Path:
    return _home() / ".local" / "state" / "overdeck" / "systray" / "runtime" / "accounts"


def target_root() -> Path:
    return _home() / ".local" / "state" / "overdeck" / "factory" / "pi-accounts"


def available_accounts() -> list[str]:
    root = registry_root()
    if not root.is_dir():
        return []
    return sorted(child.name for child in root.iterdir()
                  if child.is_dir() and (child / "PI_HOME" / "auth.json").is_file())


def materialize_account(slug: str) -> Path:
    available = available_accounts()
    if slug not in available:
        raise SystemExit(f"account {slug!r} is not defined — available: {available}")
    source = source_agent_dir()
    auth = registry_root() / slug / "PI_HOME" / "auth.json"
    parent = target_root() / slug
    target = parent / uuid4().hex
    staging = parent / f".{target.name}.tmp"
    parent.mkdir(parents=True, exist_ok=True)
    try:
        staging.mkdir()
        if source.is_dir():
            for entry in source.iterdir():
                if entry.name != "auth.json":
                    (staging / entry.name).symlink_to(entry)
        (staging / "auth.json").symlink_to(auth)
        os.replace(staging, target)
    except BaseException:
        shutil.rmtree(staging, ignore_errors=True)
        raise
    return target


def cleanup_account(target: Path) -> None:
    root = target_root().resolve()
    candidate = target.resolve()
    if candidate.parent.parent != root:
        raise ValueError(f"refusing to clean non-account directory: {target}")
    shutil.rmtree(candidate)
