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)

SEARCH_TYPE_CHOICES = click.Choice(
    ["all", "news", "images", "videos", "shopping", "books", "forums", "short_videos"],
    case_sensitive=False,
)


@click.command("search")
@click.argument("query")
@click.option("--max-results", "-n", default=10, help="Max organic results")
@click.option("--json", "json_output", is_flag=True, help="JSON output")
@click.option("--no-ai", is_flag=True, help="Skip AI Overview extraction")
@click.option("--lang", default="en", help="Search language")
@click.option("--region", default=None, help="Search region (e.g., US, CA, GB)")
@click.option("--type", "search_type", type=SEARCH_TYPE_CHOICES, default=None,
              help="Search type: all, news, images, videos, shopping, books, forums, short_videos")
@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 search_cmd(
    query, max_results, json_output, no_ai, lang, region,
    search_type, time_filter, date_from, date_to, timeout,
):
    """Search Google and return results with AI Overview."""
    async def _run():
        try:
            result = await shared.search(
                query=query,
                max_results=max_results,
                include_ai=not no_ai,
                language=lang,
                region=region,
                search_type=search_type,
                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_results(result)

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

    asyncio.run(_run())


def _print_results(result):
    """Pretty-print search results with Rich."""
    if result.ai_overview:
        console.print()
        console.print(Panel(
            result.ai_overview.text[:1000],
            title="AI Overview",
            border_style="blue",
        ))
        if result.ai_overview.sources:
            sources = ", ".join(s.domain for s in result.ai_overview.sources)
            console.print(f"  [dim]Sources: {sources}[/dim]")
        console.print()

    if result.results:
        console.print("[bold]Search Results[/bold]")
        console.print("─" * 60)
        for r in result.results:
            console.print(f"\n[bold]{r.position}. {r.title}[/bold]")
            console.print(f"   [link={r.url}]{r.url}[/link]")
            if r.snippet:
                console.print(f"   [dim]{r.snippet[:200]}[/dim]")

    if result.people_also_ask:
        console.print("\n[bold]People Also Ask[/bold]")
        console.print("─" * 60)
        for q in result.people_also_ask:
            console.print(f"  • {q}")

    if result.related_searches:
        console.print("\n[bold]Related Searches[/bold]")
        for q in result.related_searches:
            console.print(f"  • {q}")

    console.print()
