"""Centralized sheet discovery and management.

This module provides a single interface for finding and managing sheets,
abstracting away the directory structure and file handling.
All sheet discovery goes through this module - no other part of the
codebase should access sheet directories directly.
"""

from pathlib import Path
from typing import Literal

SHEETS_ROOT = Path(__file__).parent
REFERENCE_DIR = SHEETS_ROOT / "reference"
CODE_DIR = SHEETS_ROOT / "code"

SheetType = Literal["reference", "code"]


def find_sheet(name: str, sheet_type: SheetType) -> Path | None:
    """Find a sheet file by name and type.

    Args:
        name: Name of the sheet (without extension)
        sheet_type: Type of sheet ("reference" or "code")

    Returns:
        Path to the sheet file, or None if not found
    """
    search_dir = REFERENCE_DIR if sheet_type == "reference" else CODE_DIR

    if not search_dir.exists():
        return None

    for path in search_dir.glob(f"{name}.*"):
        if path.is_file():
            return path

    return None


def list_sheets(sheet_type: SheetType) -> list[Path]:
    """List all sheets of a given type.

    Args:
        sheet_type: Type of sheets to list

    Returns:
        List of paths to sheet files (excluding any __init__.py)
    """
    search_dir = REFERENCE_DIR if sheet_type == "reference" else CODE_DIR

    if not search_dir.exists():
        return []

    return [p for p in search_dir.iterdir() if p.is_file() and p.name != "__init__.py"]


def get_sheet_type(path: Path) -> SheetType:
    """Determine the type of a sheet from its path.

    Args:
        path: Path to sheet file

    Returns:
        "reference" or "code" based on directory
    """
    if "reference" in path.parts:
        return "reference"
    elif "code" in path.parts:
        return "code"
    else:
        return "reference"


def find_sheet_any_type(name: str) -> tuple[Path, SheetType] | None:
    """Find a sheet by name, checking both types.

    Args:
        name: Name of the sheet

    Returns:
        Tuple of (path, type) or None if not found
    """
    path = find_sheet(name, "reference")
    if path:
        return (path, "reference")

    path = find_sheet(name, "code")
    if path:
        return (path, "code")

    return None
