from pathlib import Path

from hatchdx.scaffolder import ScaffoldContext
from hatchdx.scaffolder.renderer import render_template


def _get_templates_dir() -> Path:
    """Return the path to the bundled templates directory."""
    return Path(__file__).parent.parent / "templates"


def _resolve_template_dir(context: ScaffoldContext) -> Path:
    """Resolve the template directory for the given context.

    Tries {language}-{transport}-{template} first (e.g., python-stdio-api-wrapper),
    then falls back to {language}-{transport} (e.g., python-stdio) for minimal/default.
    """
    templates_dir = _get_templates_dir()

    if context.template and context.template != "minimal":
        specific = templates_dir / f"{context.language}-{context.transport}-{context.template}"
        if specific.is_dir():
            return specific

    return templates_dir / f"{context.language}-{context.transport}"


def scaffold(context: ScaffoldContext, output_parent: Path | None = None) -> Path:
    """Generate a new MCP server project from a template.

    Args:
        context: The scaffold configuration.
        output_parent: Parent directory for the new project. Defaults to CWD.

    Returns:
        Path to the generated project directory.

    Raises:
        FileExistsError: If the output directory already exists.
        FileNotFoundError: If the requested template doesn't exist.
    """
    parent = output_parent or Path.cwd()
    output_dir = parent / context.server_name

    if output_dir.exists():
        raise FileExistsError(f"Directory already exists: {output_dir}")

    template_dir = _resolve_template_dir(context)

    if not template_dir.is_dir():
        raise FileNotFoundError(
            f"Template not found: {context.language}-{context.transport}"
        )

    render_template(template_dir, output_dir, context)

    return output_dir
