"""CLI implementation for `antiqa chat` — interactive AI QA session."""

from __future__ import annotations

from pathlib import Path

import typer
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel

from antiqa.config.manager import config_exists, load_config

console = Console()


def run_chat() -> None:
    """Start an interactive AI-powered QA chat session."""
    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()

    from antiqa.agents.natural_test import NaturalTestAgent
    from antiqa.browser.manager import BrowserManager
    from antiqa.crawler.graph import NavigationGraph
    from antiqa.flows.runner import FlowRunner

    graph = None
    graph_path = Path("logs/navigation_graph.json")
    if graph_path.is_file():
        graph = NavigationGraph.load(graph_path)

    console.print()
    console.print(Panel(
        "[bold cyan]AntiQA Chat[/bold cyan]  ·  Interactive QA Session\n"
        "[dim]Type test descriptions in plain English.\n"
        "Commands: /run <flow>, /flows, /visual, /health, /quit[/dim]",
        border_style="cyan",
        expand=False,
    ))
    console.print()

    test_agent = NaturalTestAgent(config, graph=graph)
    mgr: BrowserManager | None = None
    runner: FlowRunner | None = None
    last_result = None

    def _ensure_browser():
        nonlocal mgr, runner
        if mgr is None:
            mgr = BrowserManager(config.browser, logs_dir=config.logs_dir)
            page = mgr.launch()
            runner = FlowRunner(page, config=config, screenshots_dir=f"{config.logs_dir}/screenshots")
        return runner

    try:
        while True:
            try:
                user_input = console.input("[bold green]antiqa>[/bold green] ").strip()
            except (EOFError, KeyboardInterrupt):
                console.print("\n[dim]Goodbye![/dim]")
                break

            if not user_input:
                continue

            if user_input.lower() in ("/quit", "/exit", "/q"):
                console.print("[dim]Goodbye![/dim]")
                break

            if user_input.lower() == "/flows":
                from antiqa.flows.parser import FlowParser
                fp = FlowParser(config.flows_dir)
                flows = fp.list_flows()
                if flows:
                    console.print(f"\n[cyan]Available flows ({len(flows)}):[/cyan]")
                    for f in flows:
                        console.print(f"  • [bold]{f.name}[/bold] — {f.description or 'No description'}")
                else:
                    console.print("[yellow]No flows found.[/yellow]")
                console.print()
                continue

            if user_input.lower().startswith("/run "):
                flow_name = user_input[5:].strip()
                from antiqa.flows.parser import FlowParser
                fp = FlowParser(config.flows_dir)
                try:
                    flow = fp.resolve_with_includes(flow_name)
                except FileNotFoundError:
                    console.print(f"[red]Flow '{flow_name}' not found.[/red]")
                    continue
                r = _ensure_browser()
                with console.status(f"[cyan]Running {flow_name}...[/cyan]"):
                    last_result = r.run(flow)
                _print_result_summary(last_result)
                continue

            if user_input.lower() == "/visual" and last_result:
                _run_visual_review(config, last_result)
                continue

            if user_input.lower() == "/health" and last_result:
                if last_result.health_issues:
                    console.print(f"\n[yellow]{len(last_result.health_issues)} health issue(s):[/yellow]")
                    for issue in last_result.health_issues:
                        sev_color = "red" if issue.severity.value == "critical" else "yellow"
                        console.print(f"  [{sev_color}]{issue.severity.value}[/{sev_color}] "
                                       f"[dim]{issue.category.value}[/dim] — {issue.message[:80]}")
                else:
                    console.print("[green]No health issues from the last run.[/green]")
                console.print()
                continue

            # Default: treat as natural language test description
            with console.status("[cyan]AI generating test...[/cyan]"):
                try:
                    flow = test_agent.generate(user_input)
                except Exception as exc:
                    console.print(f"[red]AI error:[/red] {exc}")
                    continue

            console.print(f"\n  [green]✓[/green] Generated: [cyan]{flow.name}[/cyan] ({len(flow.steps)} steps)")

            r = _ensure_browser()
            with console.status("[cyan]Executing...[/cyan]"):
                last_result = r.run(flow)

            _print_result_summary(last_result)

    finally:
        if mgr:
            mgr.close()
        from antiqa.utils.cleanup import remove_screenshots
        remove_screenshots(f"{config.logs_dir}/screenshots")


def _print_result_summary(result) -> None:
    """Print a compact summary of a FlowResult."""
    s = result.summary()
    status = "[green]PASSED[/green] ✅" if result.passed else "[red]FAILED[/red] ❌"
    console.print(f"\n  {status}  Steps: {s['steps_passed']}/{s['steps_total']}  "
                  f"Time: {s['duration_ms']:.0f}ms")

    for step in result.steps:
        icon = "✓" if step.passed else "✗"
        color = "green" if step.passed else "red"
        console.print(f"    [{color}]{icon}[/{color}] {step.description[:60]}")

    if result.health_issues:
        console.print(f"    [yellow]⚠ {len(result.health_issues)} health issue(s)[/yellow]")

    console.print()


def _run_visual_review(config, result) -> None:
    """Run visual review on screenshots from the last test run."""
    screenshots_dir = Path(f"{config.logs_dir}/screenshots")
    screenshots = sorted(screenshots_dir.glob("*.png"))
    if not screenshots:
        console.print("[yellow]No screenshots found to review.[/yellow]")
        return

    from antiqa.agents.visual_reviewer import VisualReviewerAgent

    reviewer = VisualReviewerAgent(config)
    console.print(f"\n[cyan]Reviewing {len(screenshots)} screenshot(s)...[/cyan]")

    for ss in screenshots[-3:]:
        with console.status(f"[cyan]Reviewing {ss.name}...[/cyan]"):
            review = reviewer.review_screenshot(ss, page_url="")
        console.print(f"\n  [bold]{ss.name}[/bold] — {review.page_assessment}")
        if review.issues:
            for vi in review.issues:
                sev_color = "red" if vi.severity == "critical" else "yellow" if vi.severity == "warning" else "dim"
                console.print(f"    [{sev_color}]{vi.severity}[/{sev_color}] {vi.description[:70]}")
        else:
            console.print("    [green]No issues found[/green]")

    console.print()
