"""CLI command: asa repair — detect drift and propose/apply fixes."""

import typer

from ..core import logging as log
from ..core.paths import find_project_root
from ..engine.repairer.repairer import detect_all_issues, repair_issues
from ..engine.spec.parser import load_spec


def repair(
    auto: bool = typer.Option(False, "--auto", help="Auto-apply safe fixes (imports, one-liners)"),
    review: bool = typer.Option(True, "--review/--no-review", help="Show suggestions for manual review"),
) -> None:
    """Detect architecture drift and propose or apply fixes.

    Runs verification against .asa/spec.yaml and for each violation:
    - Auto-fixable: applies patch (with --auto) or shows suggestion
    - Manual: generates TODO with location and suggested replacement

    Default mode is --review (show suggestions, don't auto-apply).
    """
    project_root = find_project_root()

    spec = load_spec(project_root)
    if spec is None:
        log.error(
            "No .asa/spec.yaml found. Run 'asa spec infer' or 'asa init' first."
        )
        raise typer.Exit(code=2)

    log.header("ASA Repair — drift detection + fix suggestions")

    errors, warnings = detect_all_issues(project_root, spec)
    all_issues = errors + warnings

    if not all_issues:
        log.success("No drift detected — architecture matches spec.")
        raise typer.Exit(code=0)

    log.info(f"Found {len(all_issues)} issues ({len(errors)} errors, {len(warnings)} warnings)")
    print()

    manual_items = repair_issues(project_root, spec, errors, warnings, auto=auto)

    if manual_items:
        print()
        log.header("Manual items remaining:")
        for i, item in enumerate(manual_items, 1):
            log.detail(f"{i}. {item}")

    remaining = len(manual_items)
    if remaining > 0:
        print()
        log.warning(f"{remaining} items require manual intervention")
        raise typer.Exit(code=1)
    else:
        log.success("All issues resolved")
        raise typer.Exit(code=0)
