from __future__ import annotations

from pathlib import Path

# Package location: supply_agent/paths.py → project root is parent of supply_agent/
_PACKAGE_DIR = Path(__file__).resolve().parent
_DEFAULT_PROJECT_ROOT = _PACKAGE_DIR.parent


def find_project_root(start: Path | None = None) -> Path:
    """
    Find the project root directory.

    Walks upward looking for pyproject.toml or a skills/ directory.
    Falls back to the package's parent directory.
    """
    current = (start or Path.cwd()).resolve()

    for directory in [current, *current.parents]:
        if (directory / "pyproject.toml").exists():
            return directory
        if (directory / "skills").is_dir():
            return directory

    return _DEFAULT_PROJECT_ROOT


def resolve_path(path: Path | str, *, project_root: Path | None = None) -> Path:
    """
    Resolve a path relative to CWD or project root.

    Priority:
      1. Absolute paths — used as-is
      2. Relative path exists under CWD — use CWD-relative
      3. Otherwise — resolve against project root
    """
    resolved = Path(path)
    if resolved.is_absolute():
        return resolved

    root = project_root or find_project_root()
    cwd_candidate = (Path.cwd() / resolved).resolve()
    if cwd_candidate.exists():
        return cwd_candidate

    return (root / resolved).resolve()
