"""Global iEvo configuration and paths."""

from pathlib import Path

# ── Defaults ───────────────────────────────────────────────────
IEVO_MANIFEST = "ievo.yaml"
AGENTS_DIR = "agents"
SPEC_DIR = "spec"
PLANS_DIR = "plans"

MARKETPLACE_REPO = "https://github.com/ievo-ai/marketplace"
MARKETPLACE_RAW = "https://raw.githubusercontent.com/ievo-ai/marketplace/main"
REGISTRY_URL = f"{MARKETPLACE_RAW}/registry.yaml"

# ── Config directory ───────────────────────────────────────────
IEVO_HOME = Path.home() / ".ievo"
CACHE_DIR = IEVO_HOME / "cache"
PRIVATE_KEY_FILE = IEVO_HOME / "ievo_key"
PUBLIC_KEY_FILE = IEVO_HOME / "ievo_key.pub"
CREDENTIALS_FILE = IEVO_HOME / "credentials.enc"
CONFIG_FILE = IEVO_HOME / "config.json"


def ensure_home() -> Path:
    """Create ~/.ievo with key pair if it doesn't exist.

    Returns the home path. First call generates RSA keys.
    """
    first_time = not IEVO_HOME.exists()
    IEVO_HOME.mkdir(parents=True, exist_ok=True)
    CACHE_DIR.mkdir(parents=True, exist_ok=True)

    if first_time:
        from ievo.core.credentials import ensure_keys

        ensure_keys(IEVO_HOME)

    return IEVO_HOME


def find_project_root(start: Path | None = None) -> Path | None:
    """Walk up from `start` looking for ievo.yaml."""
    current = start or Path.cwd()
    for parent in [current, *current.parents]:
        if (parent / IEVO_MANIFEST).exists():
            return parent
    return None


def require_project(start: Path | None = None) -> Path:
    """Return project root or exit with error."""
    import typer

    root = find_project_root(start)
    if root is None:
        from ievo.utils.console import error

        error("Not in an iEvo project. Run [bold]ievo init[/bold] first.")
        raise typer.Exit(1)
    return root
