"""
ConfigStore: reads and writes ~/.skilark/config.yaml.

The config file is created on first setup and contains:
  user_id  - UUID assigned by the API on registration
  topics   - list of skill topics the user cares about
  api_url  - base URL for the Skilark API (default: production)
"""

import os
from pathlib import Path

import yaml

DEFAULT_API_URL = "https://api.skilark.com"


class ConfigStore:
    """Manages the on-disk configuration for the Skilark CLI.

    Uses a configurable config_dir so that tests can point at a tmp_path
    instead of touching the real ~/.skilark directory.
    """

    def __init__(self, config_dir: Path | None = None):
        self.config_dir = config_dir or Path(os.environ.get("SKILARK_CONFIG_DIR", Path.home() / ".skilark"))
        self.config_file = self.config_dir / "config.yaml"

    def is_first_run(self) -> bool:
        """Return True if no config file exists yet (i.e. not yet set up)."""
        return not self.config_file.exists()

    def save(
        self,
        user_id: str,
        topics: list[str],
        api_url: str = DEFAULT_API_URL,
    ) -> None:
        """Write a fresh config file, creating the directory if needed.

        Overwrites any existing config entirely — intended for initial setup
        or a full reset.
        """
        self.config_dir.mkdir(parents=True, exist_ok=True)
        data = {"user_id": user_id, "topics": topics, "api_url": api_url}
        self.config_file.write_text(yaml.dump(data, default_flow_style=False))

    def load(self) -> dict:
        """Load and return the config as a plain dict.

        Raises FileNotFoundError if is_first_run() is True (file not yet
        created).  Callers should check is_first_run() before calling load().
        """
        return yaml.safe_load(self.config_file.read_text())

    def update_topics(self, topics: list[str]) -> None:
        """Replace the stored topic list without touching other fields.

        Raises FileNotFoundError if config has not been created yet.
        """
        config = self.load()
        config["topics"] = topics
        self.config_file.write_text(yaml.dump(config, default_flow_style=False))
