"""Settings service: read/write config.toml from the API."""

from __future__ import annotations

import logging
import tomllib
from pathlib import Path

import tomli_w

log = logging.getLogger(__name__)


class SettingsService:
    """Reads and writes ~/.agntspace/config.toml."""

    def __init__(self, config_path: Path) -> None:
        self._path = config_path

    def get_all(self) -> dict:
        """Read the full config."""
        if not self._path.exists():
            return {}
        with open(self._path, "rb") as f:
            return tomllib.load(f)

    def get_section(self, section: str) -> dict:
        """Get a config section (e.g., 'llm', 'server')."""
        data = self.get_all()
        return data.get(section, {})

    def update_section(self, section: str, values: dict) -> dict:
        """Update a config section, merging with existing values."""
        data = self.get_all()
        if section not in data:
            data[section] = {}
        data[section].update(values)
        self._write(data)
        log.info("Config updated: [%s] %s", section, list(values.keys()))
        return data[section]

    def set_value(self, section: str, key: str, value) -> None:  # noqa: ANN001
        """Set a single config value."""
        data = self.get_all()
        if section not in data:
            data[section] = {}
        data[section][key] = value
        self._write(data)

    def get_value(self, section: str, key: str, default=None):  # noqa: ANN001
        """Get a single config value."""
        return self.get_all().get(section, {}).get(key, default)

    def _write(self, data: dict) -> None:
        self._path.parent.mkdir(parents=True, exist_ok=True)
        self._path.write_bytes(tomli_w.dumps(data).encode())
