"""asa slice new — Create a new vertical slice."""

import sys

import typer

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


def run_slice_new(
    domain_slice: str,
    *,
    slice_type: str = "route",
    no_ui: bool = False,
    no_repo: bool = False,
) -> None:
    """Create a new vertical slice with contract, skeleton, and runtime adapters."""
    from ...engine_loader import require_engine
    require_engine()
    from ...engine.contract.generator import create_contract
    from ...engine.contract.models import SliceType
    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 slice_path.exists():
            raise SliceAlreadyExistsError(f"Slice already exists: {domain}/{slice_name}")

        # Determine flags
        valid_types: list[SliceType] = ["route", "webhook", "internal-service"]
        if slice_type not in valid_types:
            log.error(f"Invalid slice type '{slice_type}'. Must be one of: {', '.join(valid_types)}")
            raise typer.Exit(1)

        has_ui = not no_ui and slice_type == "route"
        has_repository = not no_repo

        # Create contract
        contract = create_contract(
            domain,
            slice_name,
            slice_type=slice_type,  # type: ignore
            has_ui=has_ui,
            has_repository=has_repository,
        )

        # Generate all files
        created = generate_slice_files(contract, slice_path, project_root)

        # Update asa.config.json domains list
        config = load_config(project_root)
        if domain not in config.domains:
            config.domains.append(domain)
            save_config(config, project_root)

        # Output
        log.success(f"Created slice: {domain}/{slice_name} (type: {slice_type})")
        for path in created:
            log.detail(f"Created: {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)
