"""Base domain service: manages files within a vault subdirectory."""

from __future__ import annotations

from agntspace.vault.reader import VaultDocument, VaultReader
from agntspace.vault.writer import VaultWriter

DOMAIN_NAMES = (
    "projects",
    "companies",
    "contacts",
    "finances",
    "knowledge",
    "calendar",
    "health",
    "goals",
    "email",
)


class DomainService:
    """Generic domain service for any vault subdirectory.

    Each domain is simply a namespace in the vault with CRUD operations.
    """

    def __init__(
        self, name: str, vault_reader: VaultReader, vault_writer: VaultWriter
    ) -> None:
        self.name = name
        self._reader = vault_reader
        self._writer = vault_writer

    def list_files(self) -> list[dict]:
        """List all markdown files in this domain."""
        files = self._reader.list_files(self.name, "*.md")
        results = []
        for f in files:
            try:
                doc = self._reader.read(f"{self.name}/{f.name}")
                results.append({
                    "slug": f.stem,
                    "title": doc.metadata.get("title", f.stem),
                    "path": f"{self.name}/{f.name}",
                })
            except Exception:
                results.append({"slug": f.stem, "title": f.stem, "path": f"{self.name}/{f.name}"})
        return results

    def get_file(self, slug: str) -> VaultDocument | None:
        """Get a file by slug."""
        path = f"{self.name}/{slug}.md"
        if not self._reader.exists(path):
            return None
        return self._reader.read(path)

    def create_file(self, slug: str, content: str, metadata: dict | None = None) -> str:
        """Create a file in this domain."""
        path = f"{self.name}/{slug}.md"
        self._writer.write(path, content, metadata)
        return path

    def update_file(self, slug: str, content: str, metadata: dict | None = None) -> str:
        """Update a file in this domain."""
        path = f"{self.name}/{slug}.md"
        self._writer.write(path, content, metadata)
        return path

    @property
    def file_count(self) -> int:
        return len(self._reader.list_files(self.name, "*.md"))
