"""asa slice build — Run internal build pipeline (contract → zod → skeleton)."""

import typer

from ...core import logging as log
from ...core.errors import AsaError
from ...core.paths import find_project_root, parse_domain_slice, resolve_slice_path


def run_slice_build(domain_slice: str) -> None:
    """Run full build pipeline for a slice: contract → zod → skeleton."""
    from ...engine_loader import require_engine
    require_engine()
    from ...engine.contract.validator import validate_contract
    from ...engine.skeleton.generator import generate_slice_files
    try:
        domain, slice_name = parse_domain_slice(domain_slice)
        project_root = find_project_root()
        slice_path = resolve_slice_path(domain, slice_name, project_root)

        if not slice_path.exists():
            log.error(f"Slice not found: {domain}/{slice_name}")
            raise typer.Exit(1)

        contract_path = slice_path / "slice.contract.json"
        contract = validate_contract(contract_path)

        created = generate_slice_files(contract, slice_path, project_root)

        log.success(f"Built slice: {domain}/{slice_name}")
        for path in created:
            log.detail(f"Generated: {path}")

    except AsaError as e:
        log.error(str(e))
        raise typer.Exit(1)
    except typer.Exit:
        raise
    except Exception as e:
        log.error(f"[INTERNAL ERROR] {e}")
        raise typer.Exit(2)
