"""Configuration loading from pyproject.toml."""

from __future__ import annotations

import sys
from dataclasses import dataclass, field
from pathlib import Path

if sys.version_info >= (3, 11):
    import tomllib
else:
    import tomli as tomllib


@dataclass
class Config:
    """Configuration for glreview."""

    # Source patterns to discover modules (required in pyproject.toml)
    sources: list[str] = field(default_factory=list)

    # Patterns to exclude
    exclude: list[str] = field(default_factory=list)

    # Path to the registry file
    registry: str = ".glreview/registry.json"

    # GitLab issue labels
    issue_labels: list[str] = field(default_factory=lambda: ["review::pending"])

    # Path to custom issue template (optional)
    issue_template: str | None = None

    # Named reviewer teams
    teams: dict[str, list[str]] = field(default_factory=dict)

    # Project root directory
    root: Path = field(default_factory=Path.cwd)

    @property
    def registry_path(self) -> Path:
        """Get the absolute path to the registry file."""
        return self.root / self.registry


def load_config(project_root: Path | None = None) -> Config:
    """Load configuration from pyproject.toml.

    Args:
        project_root: Path to the project root. If None, searches upward
            from cwd for pyproject.toml.

    Returns:
        Config object with loaded settings.
    """
    if project_root is None:
        project_root = find_project_root()

    pyproject_path = project_root / "pyproject.toml"

    if not pyproject_path.exists():
        # Return defaults
        return Config(root=project_root)

    with open(pyproject_path, "rb") as f:
        data = tomllib.load(f)

    tool_config = data.get("tool", {}).get("glreview", {})

    return Config(
        sources=tool_config.get("sources", []),
        exclude=tool_config.get("exclude", []),
        registry=tool_config.get("registry", ".glreview/registry.json"),
        issue_labels=tool_config.get("issue_labels", ["review::pending"]),
        issue_template=tool_config.get("issue_template"),
        teams=tool_config.get("teams", {}),
        root=project_root,
    )


def find_project_root(start: Path | None = None) -> Path:
    """Find the project root by searching upward for pyproject.toml or .git.

    Args:
        start: Starting directory. Defaults to cwd.

    Returns:
        Path to the project root.

    Raises:
        FileNotFoundError: If no project root can be found.
    """
    if start is None:
        start = Path.cwd()

    current = start.resolve()

    while current != current.parent:
        if (current / "pyproject.toml").exists():
            return current
        if (current / ".git").exists():
            return current
        current = current.parent

    # Fall back to start directory
    return start.resolve()
