"""Load per-project configuration from ``.proxym.yaml``.

The file lives in the project root and provides defaults that CLI commands
(``proxym run``, ``proxym dispatch``, ``proxym do``) use when explicit flags
are not provided.

Example ``.proxym.yaml``::

    name: my-project
    default_tool: aider
    model: balanced
    timeout: 300
    context_files:
      - spec.md
      - src/types.ts
    auto_analyze: true
"""

from __future__ import annotations

import os
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any


@dataclass
class ProjectConfig:
    """Parsed ``.proxym.yaml`` with sensible defaults."""

    name: str = ""
    default_tool: str = ""
    model: str = ""
    timeout: int = 300
    context_files: list[str] = field(default_factory=list)
    auto_analyze: bool = False
    # raw dict for forward-compat with unknown keys
    _raw: dict[str, Any] = field(default_factory=dict, repr=False)

    @property
    def has_tool(self) -> bool:
        return bool(self.default_tool)

    @property
    def has_model(self) -> bool:
        return bool(self.model)


_YAML_NAMES = (".proxym.yaml", ".proxym.yml")


def load_project_config(project_dir: str | Path | None) -> ProjectConfig:
    """Load ``.proxym.yaml`` from *project_dir*.  Returns empty config on any error."""
    if not project_dir:
        return ProjectConfig()
    project_dir = Path(project_dir).expanduser().resolve()
    for name in _YAML_NAMES:
        path = project_dir / name
        if path.is_file():
            return _parse(path)
    return ProjectConfig()


def _parse(path: Path) -> ProjectConfig:
    """Parse a YAML file into *ProjectConfig*."""
    try:
        import yaml  # PyYAML — already a proxym dependency
    except ImportError:  # pragma: no cover
        return ProjectConfig()
    try:
        raw = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
    except Exception:
        return ProjectConfig()
    if not isinstance(raw, dict):
        return ProjectConfig()
    return ProjectConfig(
        name=str(raw.get("name", "")),
        default_tool=str(raw.get("default_tool", "")),
        model=str(raw.get("model", "")),
        timeout=int(raw.get("timeout", 300)),
        context_files=list(raw.get("context_files", [])),
        auto_analyze=bool(raw.get("auto_analyze", False)),
        _raw=raw,
    )
