"""Centralized path resolution — global ~/.fliiq/ with local .fliiq/ overrides."""

from pathlib import Path

GLOBAL_DIR = Path.home() / ".fliiq"


def global_fliiq_dir() -> Path:
    """Return ~/.fliiq/. Does not create it."""
    return GLOBAL_DIR


def local_fliiq_dir() -> Path | None:
    """Return .fliiq/ in cwd or parent, or None if not found."""
    current = Path.cwd()
    for parent in [current, *current.parents]:
        candidate = parent / ".fliiq"
        if candidate.is_dir():
            return candidate
    return None


def resolve_fliiq_dir(require_local: bool = False) -> Path:
    """Resolve the active .fliiq/ directory.

    Resolution order: local .fliiq/ > global ~/.fliiq/

    Args:
        require_local: If True, only return local dir (for daemon/jobs).
    """
    local = local_fliiq_dir()
    if local:
        return local
    if require_local:
        raise FileNotFoundError(
            "No local .fliiq/ directory found. Run `fliiq init --project` in your project root."
        )
    if GLOBAL_DIR.is_dir():
        return GLOBAL_DIR
    raise FileNotFoundError("No .fliiq/ directory found. Run `fliiq init` to set up.")


def load_user_profile() -> dict:
    """Load user identity from ~/.fliiq/user.yaml.

    Returns empty dict if file is missing or malformed.
    """
    import yaml

    user_yaml = GLOBAL_DIR / "user.yaml"
    if not user_yaml.is_file():
        return {}
    try:
        data = yaml.safe_load(user_yaml.read_text())
        return data if isinstance(data, dict) else {}
    except Exception:
        return {}


def resolve_env_file() -> Path | None:
    """Find the .env file to load.

    Resolution: local .env (cwd) > ~/.fliiq/.env
    """
    local_env = Path.cwd() / ".env"
    if local_env.is_file():
        return local_env
    global_env = GLOBAL_DIR / ".env"
    if global_env.is_file():
        return global_env
    return None
