"""
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 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)"
    ),
    sign: bool = typer.Option(False, "--sign", help="Sign the build"),
) -> None:
    """Build Intelligence Pack for distribution.

    Validates pack first, then builds wheel or sdist using hatchling.

    Options:
    - --output: Output directory (default: dist/)
    - --format: Build format (wheel or sdist)
    - --sign: Sign the build artifacts (requires GPG)
    """
    # Validate pack first
    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)

    # Set output directory
    output_dir = output or Path("dist")
    output_dir.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:
        cmd.extend(["-o", str(output_dir)])

    try:
        build_result = subprocess.run(cmd, check=False)
        if build_result.returncode != 0:
            raise typer.Exit(build_result.returncode)

        console.print("[green]✅ Build successful[/green]")
        console.print(f"Output: {output_dir}")

        if sign:
            console.print("[yellow]⚠️  Code signing not yet implemented[/yellow]")

    except FileNotFoundError:
        console.print("[red]❌ uv not found. Install from: https://docs.astral.sh/uv/[/red]")
        raise typer.Exit(1)
