"""Filesystem path helpers — workspace-aware.

When AlbusOS is installed as a package and used from a fresh workspace,
paths must resolve relative to the user's working directory, NOT relative
to the installed package location.

Resolution order for ``workspace_root()``:
1. Explicit env var via ``Settings.albus_root`` / legacy ``PATHWAY_REPO_ROOT`` / ``PATHWAY_ROOT``
2. Current working directory (the user's project)

Resolution order for ``package_root()`` (bundled assets):
1. The installed package's ``src/`` directory (for stdlib, templates, etc.)
"""

import os
from functools import lru_cache
from pathlib import Path


@lru_cache(maxsize=1)
def workspace_root() -> Path:
    """Return the workspace root directory.

    This is the user's project directory where skills/ and pathways/ live.

    Resolution order:
    - ``Settings.albus_root`` (reads ``ALBUS_ROOT`` env var)
    - Legacy env vars: ``PATHWAY_REPO_ROOT``, ``PATHWAY_ROOT``
    - Current working directory
    """
    from core.config import get_settings

    settings = get_settings()
    root = settings.albus_root
    if not root:
        # Legacy fallback: honour old env vars that Settings doesn't model.
        root = (os.getenv("PATHWAY_REPO_ROOT") or os.getenv("PATHWAY_ROOT") or "").strip()
    if root:
        return Path(root).expanduser().resolve()

    return Path.cwd().resolve()


# Backward compatibility alias
repo_root = workspace_root


@lru_cache(maxsize=1)
def package_root() -> Path:
    """Return the AlbusOS package root (where src/ lives).

    Used for locating bundled assets like stdlib, templates, etc.
    Falls back to workspace_root if the heuristic doesn't find a package.
    """
    here = Path(__file__).resolve()

    # Typical src-layout: <root>/src/core/common/paths.py
    # - parents[0] = common/
    # - parents[1] = core/
    # - parents[2] = src/
    # - parents[3] = <root>/
    try:
        candidate = here.parents[3]
        if (candidate / "pyproject.toml").exists():
            return candidate
    except (IndexError, Exception):
        pass

    for p in here.parents:
        if (p / "pyproject.toml").exists() and (p / "src").exists():
            return p

    return workspace_root()


def src_dir() -> Path:
    """Return the src/ directory (package internals)."""
    return package_root() / "src"


def xdg_config_dir() -> Path:
    """Return the XDG config directory for albus (~/.config/albus/)."""
    xdg = os.getenv("XDG_CONFIG_HOME", "").strip()
    if xdg:
        return Path(xdg) / "albus"
    return Path.home() / ".config" / "albus"


def xdg_data_dir() -> Path:
    """Return the XDG data directory for albus (~/.local/share/albus/)."""
    xdg = os.getenv("XDG_DATA_HOME", "").strip()
    if xdg:
        return Path(xdg) / "albus"
    return Path.home() / ".local" / "share" / "albus"


def data_dir() -> Path:
    """Return the data directory for runtime state."""
    return workspace_root() / "data"


__all__ = [
    "data_dir",
    "package_root",
    "repo_root",
    "src_dir",
    "workspace_root",
    "xdg_config_dir",
    "xdg_data_dir",
]
