"""asa slice plan — Propose slice architecture from spec."""

from pathlib import Path

import typer

from ...core import logging as log
from ...core.errors import AsaError
from ...core.paths import find_project_root


def run_slice_plan(spec_file: str) -> None:
    """Analyze spec and generate slice architecture proposal."""
    from ...engine_loader import require_engine
    require_engine()
    from ...engine.planner.planner import plan_from_spec
    try:
        spec_path = Path(spec_file).resolve()
        if not spec_path.exists():
            log.error(f"Spec file not found: {spec_file}")
            raise typer.Exit(1)

        project_root = find_project_root()
        result = plan_from_spec(spec_path, project_root)

        log.header("Proposed Slice Architecture")
        log.info(f"From: {spec_file}")
        log.info(f"Domains: {len(result['domains'])}, Slices: {result['total_slices']}")
        log.info("")

        for domain, slices in result["slices"].items():
            log.info(f"  {domain}")
            for s in slices:
                flags = []
                if s["type"] != "route":
                    flags.append(s["type"])
                if not s["has_ui"]:
                    flags.append("no-ui")
                flag_str = f" ({', '.join(flags)})" if flags else ""
                log.detail(f"  {domain}/{s['name']}{flag_str}")

        if result["dependencies"]:
            log.info("")
            log.info("  Dependencies:")
            for dep in result["dependencies"]:
                log.detail(f"  {dep['from']} → {dep['to']}")

        log.info("")
        log.success(f"Saved to: asa-plan/slices.yaml + asa-plan/architecture.md")
        log.info("Review and confirm, then run: asa slice new <name> for each slice.")

    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)
