"""Configuration settings for Carve.

Loads project-level settings from ``carvesettings.toml``, including
formatter commands that run after every disk write.
"""

from __future__ import annotations

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


@dataclass
class CarveSettings:
    """Project-level Carve settings.

    Attributes:
        formatters: Maps language name (e.g. ``"python"``) to a shell
            command template.  ``{file}`` is replaced with the absolute
            file path before execution.
        language_map: Extension-to-language overrides merged on top of the
            built-in ``EXTENSION_MAP`` (e.g. ``{".djhtml": "jinja"}``).
        import_map: Language-to-module overrides merged on top of the
            built-in ``DEFAULT_IMPORT_MAP``.
    """

    formatters: dict[str, str] = field(default_factory=dict)
    tools: dict[str, str] = field(default_factory=dict)
    sidecars: bool = True
    workspace: str | None = None
    language_map: dict[str, str] = field(default_factory=dict)
    import_map: dict[str, str] = field(default_factory=dict)


def load_settings(project_root: Path) -> CarveSettings:
    """Load ``carvesettings.toml`` from a directory.

    Returns default (empty) settings if the file is absent or unparseable.
    """
    path = project_root / "carvesettings.toml"
    if not path.is_file():
        return CarveSettings()
    try:
        data = tomllib.loads(path.read_text(encoding="utf-8"))
    except Exception:
        return CarveSettings()
    return CarveSettings(
        formatters=data.get("formatters", {}),
        tools=data.get("tools", {}),
        sidecars=data.get("sidecars", True),
        workspace=data.get("workspace"),
        language_map=data.get("language_map", {}),
        import_map=data.get("import_map", {}),
    )
