"""Utility functions for accessing bundled resources."""

import shutil
import tempfile
from importlib import resources
from pathlib import Path
from typing import Any, ContextManager


def get_bundled_resources() -> ContextManager[tuple[Path, Path]]:
    """Extract bundled snippets and templates to temporary directory.

    Returns a context manager that yields (snippets_path, templates_path).
    The temporary directory is cleaned up when the context manager exits.
    """
    # Create temporary directory
    temp_dir = Path(tempfile.mkdtemp(prefix="ai_forge_"))

    try:
        # Extract snippets
        snippets_dir = temp_dir / "snippets"
        snippets_dir.mkdir(parents=True, exist_ok=True)

        # Extract templates
        templates_dir = temp_dir / "templates"
        templates_dir.mkdir(parents=True, exist_ok=True)

        # Copy bundled resources to temp directory
        _extract_resource_dir("ai_forge.data.snippets", snippets_dir)
        _extract_resource_dir("ai_forge.data.templates", templates_dir)

        # Return context manager
        class ResourceContext:
            def __enter__(self) -> tuple[Path, Path]:
                return snippets_dir, templates_dir

            def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
                # Clean up temporary directory
                shutil.rmtree(temp_dir, ignore_errors=True)

        return ResourceContext()

    except Exception:
        # Clean up on error
        shutil.rmtree(temp_dir, ignore_errors=True)
        raise


def _extract_resource_dir(package_path: str, target_dir: Path) -> None:
    """Extract all files from a package resource directory."""
    try:
        # Get the package reference
        package_parts = package_path.split(".")
        base_package = ".".join(package_parts[:-1])
        resource_dir = package_parts[-1]

        # Use importlib.resources to traverse the directory
        package_ref = resources.files(base_package)
        resource_ref = package_ref / resource_dir

        if resource_ref.is_dir():
            _copy_resource_tree(resource_ref, target_dir)
        else:
            raise FileNotFoundError(f"Resource directory {package_path} not found")

    except Exception as e:
        raise FileNotFoundError(f"Failed to extract {package_path}: {e}")


def _copy_resource_tree(resource_ref: Any, target_dir: Path) -> None:
    """Recursively copy a resource tree to target directory."""
    target_dir.mkdir(parents=True, exist_ok=True)

    for item in resource_ref.iterdir():
        target_path = target_dir / item.name

        if item.is_dir():
            # Recursively copy subdirectories
            _copy_resource_tree(item, target_path)
        else:
            # Copy file
            content = item.read_bytes()
            target_path.write_bytes(content)
