import asyncio

import click
from rich.console import Console

from gsearch_mcp_cli import shared
from gsearch_mcp_cli.exceptions import GSearchError

console = Console()


@click.command("fetch")
@click.argument("url")
@click.option("--raw", is_flag=True, help="Output plain text instead of markdown")
@click.option("--json", "json_output", is_flag=True, help="JSON output")
@click.option("--browser", type=click.Choice(["auto", "always", "never"]),
              default="auto", help="Browser usage mode")
@click.option("--timeout", default=30, type=float, help="Timeout in seconds")
def fetch_cmd(url, raw, json_output, browser, timeout):
    """Fetch a URL and return its content."""
    async def _run():
        try:
            fmt = "txt" if raw else "md"
            result = await shared.fetch(
                url=url,
                format=fmt,
                use_browser=browser,
                timeout=timeout,
            )

            if json_output:
                click.echo(result.model_dump_json(indent=2))
            else:
                _print_fetch_result(result, raw=raw)

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

    asyncio.run(_run())


def _print_fetch_result(result, *, raw=False):
    """Print fetched content."""
    if not raw:
        console.print(f"\n[bold]{result.title}[/bold]")
        console.print(f"[dim]{result.url}  •  {result.word_count} words[/dim]\n")
    click.echo(result.content)
