from __future__ import annotations

import os
from pathlib import Path


PACKAGE_DIR = Path(__file__).resolve().parents[1]
SOURCE_DIR = PACKAGE_DIR.parent


def find_project_root(start: Path = PACKAGE_DIR) -> Path:
    """Find the closest project root without depending on the current directory."""
    current = start.resolve()
    if current.is_file():
        current = current.parent
    for candidate in (current, *current.parents):
        if (candidate / "pyproject.toml").is_file():
            return candidate
    return SOURCE_DIR.parent.resolve()


def resolve_from(base: Path, value: str | os.PathLike[str]) -> Path:
    """Resolve relative configuration paths against a stable, explicit base."""
    path = Path(value).expanduser()
    if not path.is_absolute():
        path = base / path
    return path.resolve()


def resolve_project_root(value: str | os.PathLike[str] | None = None) -> Path:
    configured = value if value is not None else os.getenv("KEEPEDU_PROJECT_ROOT")
    if configured:
        path = Path(configured).expanduser()
        if not path.is_absolute():
            raise ValueError("KEEPEDU_PROJECT_ROOT deve ser um caminho absoluto.")
        return path.resolve()
    return find_project_root()


PROJECT_ROOT = resolve_project_root()


def find_repo_root(project_root: Path = PROJECT_ROOT) -> Path:
    """Find the workspace root while supporting the legacy single-project layout."""
    project_root = project_root.resolve()
    for candidate in (project_root, *project_root.parents):
        if (candidate / ".git").exists():
            return candidate
    if project_root.name == "backend" and (
        (project_root.parent / "frontend").is_dir()
        or (project_root.parent / "dashboard").is_dir()
    ):
        return project_root.parent.resolve()
    return project_root


REPO_ROOT = find_repo_root()


def resolve_env_file(value: str | os.PathLike[str] | None = None) -> Path:
    """Resolve an explicit env file, defaulting to the legacy root .env."""
    configured = value if value is not None else os.getenv("PROJECT_ENV_FILE")
    return resolve_from(REPO_ROOT, configured or ".env")


ENV_FILE = resolve_env_file()
