"""
Module: build_command
Description: Pack building command

Implements:
    - docs/cli/reference.md#huitzo-build
"""

import subprocess
from pathlib import Path
from typing import Optional

import typer
from rich.console import Console

from huitzo_cli.validator import PackValidator

console = Console()


def _do_build(
    output_dir: Path | None = None,
    format_type: str = "wheel",
) -> Path:
    """Build a wheel or sdist, returning the output directory.

    Validates the pack, runs ``uv build``, and returns the output directory.
    Raises ``typer.Exit(1)`` on any failure so callers don't need to handle
    errors individually.

    Args:
        output_dir: Where to place the built artifact (default: ``dist/``).
        format_type: ``"wheel"`` or ``"sdist"``.

    Returns:
        The resolved output directory.
    """
    validator = PackValidator()
    result = validator.validate()

    if not result.valid:
        console.print("[red]Pack validation failed[/red]")
        for error in result.errors:
            console.print(f"  {error}")
        raise typer.Exit(1)

    out = output_dir or Path("dist")
    out.mkdir(parents=True, exist_ok=True)

    console.print("[bold]Building pack...[/bold]")

    cmd = ["uv", "build"]

    if format_type == "wheel":
        cmd.append("--wheel")
    elif format_type == "sdist":
        cmd.append("--sdist")
    else:
        console.print(f"[red]Unknown format: {format_type}[/red]")
        raise typer.Exit(1)

    if output_dir:
        cmd.extend(["-o", str(out)])

    try:
        build_result = subprocess.run(cmd, check=False)
        if build_result.returncode != 0:
            raise typer.Exit(build_result.returncode)
    except FileNotFoundError:
        console.print("[red]uv not found. Install from: https://docs.astral.sh/uv/[/red]")
        raise typer.Exit(1)

    console.print("[green]Build successful[/green]")
    return out


def build(
    output: Optional[Path] = typer.Option(None, "--output", "-o", help="Output directory"),
    format_type: str = typer.Option(
        "wheel", "--format", "-f", help="Build format (wheel or sdist)"
    ),
) -> None:
    """Build Intelligence Pack for distribution.

    Validates pack first, then builds wheel or sdist using uv build.

    Options:
    - --output: Output directory (default: dist/)
    - --format: Build format (wheel or sdist)
    """
    output_dir = _do_build(output_dir=output, format_type=format_type)
    console.print(f"Output: {output_dir}")
