"""Registry configuration for the skill store.

Reads and writes the ``[skills]`` section of ``~/.icarus/config.toml``.
If absent, returns the default public registry.
"""

from __future__ import annotations

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

from icarus.config.model_config import DEFAULT_CONFIG_PATH
from icarus.utils.toml import load_toml, save_toml

logger = logging.getLogger(__name__)


@dataclass
class RegistryEntry:
    """A single skill registry pointer."""

    name: str
    url: str  # "github:owner/repo"
    token_env: str = ""  # env var name for private repos


def _default_registries() -> list[RegistryEntry]:
    return [RegistryEntry("icarus", "github:Mekopa-Labs/icarus-skills")]


@dataclass
class SkillsConfig:
    """Parsed ``[skills]`` section from config.toml."""

    registries: list[RegistryEntry] = field(default_factory=list)

    @classmethod
    def load(cls, config_path: Path | None = None) -> SkillsConfig:
        """Load from config.toml.  Returns default registry if absent."""
        if config_path is None:
            config_path = DEFAULT_CONFIG_PATH

        data = load_toml(config_path)
        skills_section = data.get("skills", {})

        # If there's no [skills] section at all, use defaults.
        # If it exists (even with an empty registries list), respect it —
        # the user may have intentionally removed all registries.
        if "registries" not in skills_section:
            return cls(registries=_default_registries())

        raw_registries = skills_section["registries"]
        entries = []
        for r in raw_registries:
            if isinstance(r, dict) and "name" in r and "url" in r:
                entries.append(RegistryEntry(
                    name=r["name"],
                    url=r["url"],
                    token_env=r.get("token_env", ""),
                ))
        return cls(registries=entries)

    def save(self, config_path: Path | None = None) -> None:
        """Write registries back to the ``[skills]`` section of config.toml."""
        if config_path is None:
            config_path = DEFAULT_CONFIG_PATH

        data = load_toml(config_path)

        registries_list = []
        for entry in self.registries:
            d: dict = {"name": entry.name, "url": entry.url}
            if entry.token_env:
                d["token_env"] = entry.token_env
            registries_list.append(d)

        data.setdefault("skills", {})["registries"] = registries_list
        save_toml(config_path, data)

    def add_registry(self, entry: RegistryEntry) -> None:
        """Add a registry, replacing any existing entry with the same name."""
        self.registries = [r for r in self.registries if r.name != entry.name]
        self.registries.append(entry)

    def remove_registry(self, name: str) -> None:
        """Remove a registry by name.  Raises ValueError if not found."""
        before = len(self.registries)
        self.registries = [r for r in self.registries if r.name != name]
        if len(self.registries) == before:
            msg = f"Registry '{name}' not found"
            raise ValueError(msg)
