"""asa slice split — Analyze oversized slice and propose split."""

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_split(domain_slice: str) -> None:
    """Analyze oversized slice and propose split."""
    from ...engine_loader import require_engine
    require_engine()
    from ...engine.splitter.splitter import analyze_slice, propose_split
    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)

        analysis = analyze_slice(slice_path, domain, slice_name)

        log.header(f"Slice Analysis: {domain}/{slice_name}")
        log.info(f"  LOC: {analysis['total_loc']}")
        log.info(f"  Public functions: {analysis['public_functions']}")
        log.info(f"  Responsibilities detected: {analysis['responsibilities_detected']}")
        log.info(f"  Cross-domain imports: {analysis['cross_domain_imports']}")

        if not analysis["is_oversized"]:
            log.success(f"Slice is within size limits ({analysis['total_loc']} LOC)")
            raise typer.Exit(0)

        log.warning(f"Slice {domain}/{slice_name} is oversized ({analysis['total_loc']} LOC)")

        proposals = propose_split(analysis)
        if proposals:
            log.header("Suggested split:")
            for p in proposals:
                log.info(f"  {p['name']} (est. ~{p['estimated_loc']} LOC)")
                for fn in p["functions"]:
                    log.detail(f"    {fn}")
            log.info("")
            log.info("To create split targets, run: asa slice new <name> for each proposed slice.")
            log.warning("Business logic must be moved manually — CLI only creates structure.")
        else:
            log.info("No clear split candidates detected. Consider manual refactoring.")

    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)
