"""Configuration management for Lettera."""

import json
from dataclasses import dataclass
from pathlib import Path


@dataclass
class Config:
    """User configuration for Lettera."""

    entries_dir: str

    @classmethod
    def get_config_path(cls) -> Path:
        """Get path to config file."""
        return Path.home() / ".lettera" / "config.json"

    @classmethod
    def get_default_entries_dir(cls) -> str:
        """Get default entries directory."""
        return str(Path.home() / ".lettera" / "entries")

    @classmethod
    def load(cls) -> "Config":
        """Load config from disk, using defaults if not found."""
        config_path = cls.get_config_path()

        if not config_path.exists():
            config = cls(entries_dir=cls.get_default_entries_dir())
            config.save()
            return config

        try:
            with open(config_path, 'r') as f:
                data = json.load(f)
            return cls(
                entries_dir=data.get("entriesDir", cls.get_default_entries_dir())
            )
        except Exception:
            # If config is corrupted, return defaults
            return cls(entries_dir=cls.get_default_entries_dir())

    def save(self) -> None:
        """Save config to disk."""
        config_path = self.get_config_path()
        config_path.parent.mkdir(parents=True, exist_ok=True)

        with open(config_path, 'w') as f:
            json.dump({"entriesDir": self.entries_dir}, f, indent=2)
