"""Calf manager for .calf file operations.

.calf files are plaintext directive documents - no metadata, no structure.
Just the raw instruction for Cleave to process.
"""

from pathlib import Path


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

    Simple file I/O operations for plaintext .calf files.
    """

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

        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 search. Uses self.directory if not provided.

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

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

        Args:
            path: Path to the .calf file.

        Returns:
            The directive text content.

        Raises:
            FileNotFoundError: If the file doesn't exist.
            PermissionError: If the file can't be read.
        """
        return path.read_text().strip()

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

        Args:
            path: Path to write to. Will create parent directories if needed.
            content: Directive text content.

        Raises:
            PermissionError: If the file can't be written.
        """
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(content.strip() + "\n")

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

        Args:
            path: Path to check.

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

    def generate_filename(self, hint: str) -> Path:
        """Generate a unique .calf filename based on a hint.

        Args:
            hint: Text hint for generating the filename (e.g., first few words).

        Returns:
            Path that doesn't exist yet.
        """
        # Clean the hint to make a valid filename
        clean = "".join(c if c.isalnum() or c in "-_" else "-" for c in hint.lower())
        clean = "-".join(part for part in clean.split("-") if part)[:30]

        base = self.directory / f"{clean}.calf"
        if not base.exists():
            return base

        # Add numeric suffix if needed
        counter = 1
        while True:
            candidate = self.directory / f"{clean}-{counter}.calf"
            if not candidate.exists():
                return candidate
            counter += 1
