"""Config parsing and validation for Super Memory."""

from __future__ import annotations

import os
from pathlib import Path

import yaml


def memory_root(start: Path | None = None) -> Path:
    """Return the .memory/ directory path, searching upward from start."""
    p = start or Path.cwd()
    while True:
        candidate = p / ".memory"
        if candidate.is_dir():
            return candidate
        if p.parent == p:
            break
        p = p.parent
    return Path.cwd() / ".memory"


def load_config(root: Path | None = None) -> dict:
    """Load config.yaml from the .memory directory."""
    root = root or memory_root()
    config_path = root / "config.yaml"
    if not config_path.exists():
        return {}
    with open(config_path) as f:
        return yaml.safe_load(f) or {}


def get_current_user(root: Path | None = None) -> str | None:
    """Get the current user identity from env var or .me file."""
    env_user = os.environ.get("MEMORY_USER")
    if env_user:
        return env_user.strip()
    root = root or memory_root()
    me_file = root / ".me"
    if me_file.exists():
        return me_file.read_text().strip()
    return None


def detect_project_name() -> str:
    """Auto-detect project name from git remote or directory name."""
    try:
        import subprocess

        result = subprocess.run(
            ["git", "remote", "get-url", "origin"],
            capture_output=True, text=True, timeout=5,
        )
        if result.returncode == 0:
            url = result.stdout.strip()
            # Extract repo name from URL
            name = url.rstrip("/").rsplit("/", 1)[-1]
            return name.removesuffix(".git")
    except (FileNotFoundError, subprocess.TimeoutExpired):
        pass
    return Path.cwd().name
