import asyncio

import click
from rich.console import Console
from rich.panel import Panel

from gsearch_mcp_cli import shared
from gsearch_mcp_cli.exceptions import GSearchError

console = Console()


TIME_CHOICES = click.Choice(["hour", "1h", "12h", "day", "24h", "week", "7d", "month", "year"], case_sensitive=False)


@click.command("ai")
@click.argument("query")
@click.option("--json", "json_output", is_flag=True, help="JSON output")
@click.option("--lang", default="en", help="Search language")
@click.option("--region", default=None, help="Search region (e.g., US, CA, GB)")
@click.option("--time", "time_filter", type=TIME_CHOICES, default=None,
              help="Time filter: hour, day, week, month, year")
@click.option("--after", "date_from", default=None, help="Results after date (YYYY-MM-DD)")
@click.option("--before", "date_to", default=None, help="Results before date (YYYY-MM-DD)")
@click.option("--timeout", default=30, type=float, help="Timeout in seconds")
def ai_cmd(query, json_output, lang, region, time_filter, date_from, date_to, timeout):
    """Run a Google AI Mode search and return synthesized results."""
    async def _run():
        try:
            result = await shared.ai_search(
                query=query,
                language=lang,
                region=region,
                time_filter=time_filter,
                date_from=date_from,
                date_to=date_to,
                timeout=timeout,
            )

            if json_output:
                click.echo(result.model_dump_json(indent=2))
            else:
                _print_ai_result(result)

        except GSearchError as e:
            console.print(f"[red]Error:[/red] {e}")
            raise SystemExit(1)
        finally:
            await shared.shutdown()

    asyncio.run(_run())


def _print_ai_result(result):
    """Pretty-print AI Mode results with Rich panels."""
    if result.synthesis:
        console.print()
        console.print(Panel(
            result.synthesis,
            title=f"AI Synthesis — {result.query}",
            border_style="green",
        ))

    if result.sections:
        for section in result.sections:
            body_parts = []
            if section.content:
                body_parts.append(section.content)
            if section.items:
                body_parts.extend(f"  • {item}" for item in section.items)
            console.print(Panel(
                "\n".join(body_parts) if body_parts else "[dim]No content[/dim]",
                title=section.heading,
                border_style="cyan",
            ))

    if result.sources:
        console.print("\n[bold]Sources[/bold]")
        console.print("─" * 60)
        for src in result.sources:
            console.print(f"  [link={src.url}]{src.domain}[/link] — {src.title}")

    console.print()
