"""asa ui generate — Regenerate frontend part of slice."""

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,
    component_name,
    hook_name,
)
from ...core.fs import ensure_directory, safe_write_file


def run_ui_generate(domain_slice: str) -> None:
    """Regenerate frontend files (hook + component) for a slice."""
    from ...engine_loader import require_engine
    require_engine()
    from ...engine.contract.validator import validate_contract
    from ...engine.skeleton.generator import _write_ui, _write_runtime_adapters
    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)

        if not contract.has_ui:
            log.warning(f"Slice {domain}/{slice_name} has has_ui=false. Skipping UI generation.")
            raise typer.Exit(0)

        created = _write_ui(contract, slice_path)
        adapter_files = _write_runtime_adapters(contract, project_root)
        created.extend(adapter_files)

        log.success(f"UI regenerated: {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)
