"""asa slice update — Regenerate slice after spec/contract change."""

import typer

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


def run_slice_update(domain_slice: str) -> None:
    """Regenerate slice files, preserving user code between markers."""
    from ...engine_loader import require_engine
    require_engine()
    from ...engine.contract.validator import validate_contract
    from ...engine.skeleton.generator import generate_slice_files
    from ...engine.regenerator.regenerator import regenerate_file_with_markers
    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)

        # Regenerate files with marker preservation
        created = generate_slice_files(contract, slice_path, project_root)

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

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