"""Calf manager service for .calf file I/O operations."""

from __future__ import annotations

import re
from pathlib import Path


class CalfManager:
    """Manages .calf directive files.

    .calf files contain plaintext directives - no YAML metadata, no structured format.
    The filename is auto-generated from the first ~30 characters of the directive.

    Interface:
        list_calves(directory?) -> list[Path] - List all .calf files
        read_calf(path) -> str - Read plaintext content
        write_calf(path, content) -> None - Write plaintext content
        exists(path) -> bool - Check if file exists
        generate_filename(hint) -> Path - Generate unique filename from hint
    """

    def __init__(self, directory: Path | None = None):
        """Initialize CalfManager.

        Args:
            directory: Working directory for .calf files. Defaults to cwd.
        """
        self.directory = directory or Path.cwd()

    def list_calves(self, directory: Path | None = None) -> list[Path]:
        """List all .calf files in a directory.

        Args:
            directory: Directory to scan. Defaults to working directory.

        Returns:
            Sorted list of .calf file paths.
        """
        scan_dir = directory or self.directory
        if not scan_dir.exists():
            return []
        return sorted(scan_dir.glob("*.calf"))

    def read_calf(self, path: Path) -> str:
        """Read a .calf file.

        Args:
            path: Path to the .calf file.

        Returns:
            Plaintext content of the file.

        Raises:
            FileNotFoundError: If file doesn't exist.
        """
        return path.read_text()

    def write_calf(self, path: Path, content: str) -> None:
        """Write a .calf file.

        Args:
            path: Path to write to.
            content: Plaintext directive content.
        """
        path.write_text(content)

    def exists(self, path: Path) -> bool:
        """Check if a .calf file exists.

        Args:
            path: Path to check.

        Returns:
            True if file exists.
        """
        return path.exists()

    def generate_filename(self, hint: str) -> Path:
        """Generate a unique filename from a hint string.

        Args:
            hint: Short text to use as filename basis (first ~30 chars of directive).

        Returns:
            Unique Path that doesn't conflict with existing files.
        """
        # Clean the hint: lowercase, replace spaces with hyphens, remove special chars
        clean = re.sub(r"[^a-z0-9\s-]", "", hint.lower())
        clean = re.sub(r"\s+", "-", clean.strip())
        clean = clean[:30].rstrip("-")

        if not clean:
            clean = "directive"

        base_path = self.directory / f"{clean}.calf"

        # Auto-increment on collision
        if not base_path.exists():
            return base_path

        counter = 1
        while True:
            numbered_path = self.directory / f"{clean}-{counter}.calf"
            if not numbered_path.exists():
                return numbered_path
            counter += 1
