"""CLI implementation for `antiqa audit` — AI accessibility audit."""

from __future__ import annotations

from pathlib import Path

import typer
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

from antiqa.config.manager import config_exists, load_config

console = Console()


def run_accessibility_audit(
    headed: bool | None = None,
    max_pages: int = 10,
) -> None:
    """Crawl pages and run AI-powered accessibility audit."""
    if not config_exists():
        console.print("[red]No antiqa.json found. Run [bold]antiqa init[/bold] first.[/red]")
        raise typer.Exit(code=2)

    config = load_config()
    if headed is not None:
        config.browser.headless = not headed

    from antiqa.agents.accessibility_auditor import AccessibilityAuditorAgent
    from antiqa.browser.manager import BrowserManager
    from antiqa.crawler.graph import NavigationGraph

    console.print()
    console.print(Panel(
        "[bold cyan]AntiQA[/bold cyan]  ·  Accessibility Audit\n"
        f"[dim]Target: {config.app_url}  |  Max pages: {max_pages}[/dim]",
        border_style="cyan",
        expand=False,
    ))

    graph_path = Path("logs/navigation_graph.json")
    if graph_path.is_file():
        graph = NavigationGraph.load(graph_path)
        pages_to_audit = list(graph.nodes.values())[:max_pages]
    else:
        console.print("[yellow]No navigation graph found. Auditing just the home page.[/yellow]")
        console.print("[dim]Run `antiqa crawl` first for a comprehensive audit.[/dim]\n")
        pages_to_audit = None

    mgr = BrowserManager(config.browser, logs_dir=config.logs_dir)
    page = mgr.launch()
    auditor = AccessibilityAuditorAgent(config)

    all_results = []

    try:
        if pages_to_audit:
            for i, node in enumerate(pages_to_audit, 1):
                url = f"{config.app_url}{node.url_pattern}"
                console.print(f"  [{i}/{len(pages_to_audit)}] Auditing [cyan]{url}[/cyan]...")
                try:
                    page.goto(url, wait_until="domcontentloaded", timeout=10000)
                except Exception:
                    console.print(f"    [yellow]Could not load page, skipping[/yellow]")
                    continue

                with console.status("[cyan]AI analysing..."):
                    result = auditor.audit_page(page, url)
                all_results.append(result)

                issue_count = len(result.issues)
                score_color = "green" if result.score in ("AA", "AAA") else "yellow" if result.score == "A" else "red"
                console.print(f"    Score: [{score_color}]{result.score}[/{score_color}] — {issue_count} issue(s)")
        else:
            url = config.app_url
            console.print(f"  Auditing [cyan]{url}[/cyan]...")
            page.goto(url, wait_until="domcontentloaded", timeout=10000)
            with console.status("[cyan]AI analysing..."):
                result = auditor.audit_page(page, url)
            all_results.append(result)
    finally:
        mgr.close()

    # Render results
    console.print()

    total_issues = sum(len(r.issues) for r in all_results)
    critical = sum(1 for r in all_results for i in r.issues if i.severity == "critical")
    warnings = sum(1 for r in all_results for i in r.issues if i.severity == "warning")

    if total_issues > 0:
        table = Table(
            title=f"Accessibility Issues ({total_issues} total)",
            show_lines=True,
            title_style="bold yellow",
        )
        table.add_column("Page", style="cyan", max_width=30)
        table.add_column("Severity", width=10)
        table.add_column("WCAG", width=20)
        table.add_column("Issue", max_width=40)
        table.add_column("Fix", style="dim", max_width=40)

        for result in all_results:
            page_label = result.page_url.replace(config.app_url, "") or "/"
            for issue in result.issues:
                sev_color = "red" if issue.severity == "critical" else "yellow" if issue.severity == "warning" else "dim"
                table.add_row(
                    page_label,
                    f"[{sev_color}]{issue.severity}[/{sev_color}]",
                    issue.wcag_criterion,
                    issue.description[:40],
                    issue.fix[:40],
                )

        console.print(table)

    # Summary
    console.print()
    console.print(Panel(
        f"[bold]Accessibility Audit Complete[/bold]\n\n"
        f"Pages audited: {len(all_results)}\n"
        f"Total issues: {total_issues}  "
        f"([red]{critical} critical[/red], [yellow]{warnings} warnings[/yellow])\n"
        + ("\n".join(f"  [green]✓[/green] {c}" for r in all_results for c in r.passed_checks[:3]) if all_results else ""),
        border_style="yellow" if total_issues > 0 else "green",
        expand=False,
    ))
