"""Collection CRUD operations."""

from pathlib import Path

from mykb.core.config import get_config, save_config
from mykb.core.models import CollectionConfig


def add_collection(
    name: str,
    path: str,
    mask: str = '**/*.md',
    exclude: list[str] | None = None,
    description: str = '',
    source: str = 'obsidian',
) -> CollectionConfig:
    config = get_config()
    collections = config.setdefault('collections', {})

    if name in collections:
        raise ValueError(f"Collection '{name}' already exists")

    resolved_path = str(Path(path).expanduser().resolve())
    if not Path(resolved_path).is_dir():
        raise ValueError(f'Path does not exist or is not a directory: {resolved_path}')

    col = CollectionConfig(
        source=source,
        path=resolved_path,
        mask=mask,
        exclude=exclude or [],
        description=description,
    )
    collections[name] = col.model_dump()
    save_config(config)
    return col


def list_collections() -> dict[str, CollectionConfig]:
    config = get_config()
    collections = config.get('collections', {})
    return {name: CollectionConfig(**data) for name, data in collections.items()}


def remove_collection(name: str):
    config = get_config()
    collections = config.get('collections', {})
    if name not in collections:
        raise ValueError(f"Collection '{name}' not found")
    del collections[name]
    save_config(config)


def get_collection(name: str) -> CollectionConfig:
    config = get_config()
    collections = config.get('collections', {})
    if name not in collections:
        raise ValueError(f"Collection '{name}' not found")
    return CollectionConfig(**collections[name])
