"""API repair — detect route drift and AI-propose Maeris registry updates."""

from __future__ import annotations

from pathlib import Path

import click
from rich.console import Console

from maeris_mcp.drift_detector import detect_api_drift
from maeris_mcp.drift_detector.models import DriftIssue, DriftKind, RepairResult


async def repair_api(
    client,
    scan_root: Path,
    model: str,
    dry_run: bool,
    yes: bool,
) -> RepairResult:
    """Detect API route drift and AI-propose registry fixes.

    For ROUTE_MISSING: ask AI whether to delete or update the Maeris entry.
    For ROUTE_UNREGISTERED: suggest registering the new route.

    Args:
        client: Active MaerisClient.
        scan_root: Backend source root.
        model: Claude model for suggestions.
        dry_run: Print proposals but do not apply.
        yes: Auto-approve all suggestions.

    Returns:
        RepairResult with fixed/skipped/failed counts.
    """
    from maeris_mcp.ai_adapter.repair_suggestions import suggest_api_update
    from maeris_mcp.maeris.types import MaerisAPI

    report = await detect_api_drift(client, scan_root)
    result = RepairResult()
    console = Console()

    if not report.has_drift:
        return result

    total = len(report.issues)

    for i, issue in enumerate(report.issues, 1):
        label = f"[{i}/{total}]"
        click.echo(f"\n  {label} {issue.description}")

        if issue.kind == DriftKind.ROUTE_UNREGISTERED:
            method = issue.detail.get("method", "GET")
            path = issue.detail.get("path", "")

            if dry_run:
                click.echo(
                    f"  → Route {click.style(method, bold=True)} "
                    f"{click.style(path, fg='cyan')} not in Maeris."
                )
                click.secho("  [dry-run] Would register this route.", fg="cyan")
                result.skipped += 1
                continue

            # Build a human-readable name from the path
            name_parts = [s for s in path.strip("/").split("/") if s and s != "{param}"]
            api_name = " ".join(name_parts).replace("api ", "").title() or path

            try:
                api = MaerisAPI(url=path, type=method, name=api_name)
                api_id = await client.create_api(api)
                click.secho(
                    f"  ✓ Registered {click.style(method, bold=True)} "
                    f"{click.style(path, fg='cyan')} in Maeris.",
                    fg="green",
                )
                result.fixed += 1
            except Exception as e:
                click.secho(f"  ✗ Failed to register: {e}", fg="red")
                result.failed += 1
            continue

        # ROUTE_MISSING: Maeris has an API that no longer exists in code
        try:
            with console.status(f"  [bold cyan]Analyzing…", spinner="dots"):
                fix = suggest_api_update(issue, model)
        except Exception as e:
            click.secho(f"  ✗ AI suggestion failed: {e}", fg="red")
            result.failed += 1
            continue

        action = fix.get("action", "ignore")
        reason = fix.get("reason", "")
        proposed_url = fix.get("proposed_url", "")

        click.echo(f"  AI recommends: {click.style(action, bold=True)}")
        if reason:
            click.echo(f"  Reason: {reason}")
        if proposed_url:
            click.echo(f"  Proposed URL: {click.style(proposed_url, fg='green')}")

        if action == "ignore" or dry_run:
            if dry_run and action != "ignore":
                click.secho("  [dry-run] Would apply this action.", fg="cyan")
            result.skipped += 1
            continue

        # Confirm destructive actions individually unless --yes was passed
        if not yes:
            try:
                if not click.confirm(f"  Apply '{action}'?", default=True):
                    click.echo("  Skipped.")
                    result.skipped += 1
                    continue
            except click.Abort:
                click.echo("  Skipped.")
                result.skipped += 1
                continue

        try:
            if action == "delete":
                await client.delete_api(issue.resource_id)
                click.secho("  ✓ Deleted from Maeris.", fg="green")
                result.fixed += 1
            elif action == "update" and proposed_url:
                await client.update_api(issue.resource_id, {"url": proposed_url})
                click.secho("  ✓ URL updated in Maeris.", fg="green")
                result.fixed += 1
            else:
                result.skipped += 1
        except Exception as e:
            click.secho(f"  ✗ Failed to apply: {e}", fg="red")
            result.failed += 1

    return result
