"""
Gather SDK CLI - Connect Google ADK agents to Gather.is workspaces

Commands:
    gathersdk serve      Start the SDK bridge (requires 'adk web' running)
    gathersdk discover   List agents found in directory

Run 'adk web' in a separate terminal for full ADK debugging at http://localhost:8000
"""

import asyncio
import logging
import sys
from pathlib import Path

import click

from .sdk import AgencySDK
from .discovery import discover_agents


@click.group()
@click.option("--verbose", "-v", is_flag=True, help="Enable debug logging")
def cli(verbose: bool):
    """Gather SDK - Connect Google ADK agents to Gather.is workspaces"""
    level = logging.DEBUG if verbose else logging.INFO
    logging.basicConfig(
        level=level,
        format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
        datefmt="%H:%M:%S"
    )


@cli.command()
@click.option(
    "--config", "-c",
    default="gather.config.json",
    help="Path to config file"
)
@click.option(
    "--dir", "-d",
    default=".",
    help="Directory to search for agents"
)
@click.option(
    "--adk-url",
    default="http://localhost:8000",
    help="ADK web server URL (run 'adk web' separately)"
)
def serve(config: str, dir: str, adk_url: str):
    """
    Start the SDK bridge connecting Tinode to ADK agents.

    IMPORTANT: You must run 'adk web' separately for full ADK integration:

    \b
    Terminal 1: adk web --port 8000
    Terminal 2: gathersdk serve

    This gives you full ADK debugging at http://localhost:8000
    """
    config_path = Path(config)

    if not config_path.exists():
        click.echo(f"Config file not found: {config}", err=True)
        click.echo("\nTo get a config file:")
        click.echo("  1. Go to your workspace settings in the web UI")
        click.echo("  2. Click 'SDK Access'")
        click.echo("  3. Download gather.config.json")
        sys.exit(1)

    try:
        sdk = AgencySDK.from_config(config_path, adk_server_url=adk_url)
    except Exception as e:
        click.echo(f"Failed to load config: {e}", err=True)
        sys.exit(1)

    # Run the async discover and serve
    try:
        asyncio.run(_serve_async(sdk, dir, adk_url))
    except KeyboardInterrupt:
        click.echo("\nShutting down...")
    except Exception as e:
        click.echo(f"Error: {e}", err=True)
        sys.exit(1)


async def _serve_async(sdk: AgencySDK, dir: str, adk_url: str):
    """Async portion of serve command"""
    import httpx
    from .discovery import discover_agents

    # First discover agents locally
    agents = discover_agents(dir)

    if not agents:
        raise click.ClickException(
            f"No agents found!\n\n"
            f"Searched in: {Path(dir).resolve()}\n\n"
            f"Expected structure:\n"
            f"  agents/\n"
            f"      my_agent/\n"
            f"          __init__.py  # from .agent import root_agent\n"
            f"          agent.py     # root_agent = Agent(...)"
        )

    click.echo(f"Found {len(agents)} agent(s): {', '.join(f'@{a.handle}' for a in agents)}")

    # Check ADK web server is running
    click.echo(f"\nChecking ADK server at {adk_url}...")
    try:
        async with httpx.AsyncClient(timeout=5.0) as client:
            resp = await client.get(f"{adk_url}/list-apps")
            if resp.status_code == 200:
                click.echo(click.style("  ADK server is running", fg="green"))
            else:
                click.echo(click.style(f"  ADK server returned {resp.status_code}", fg="yellow"))
    except httpx.ConnectError:
        click.echo(click.style("  WARNING: ADK server not reachable!", fg="red"))
        click.echo()
        click.echo("  Start the ADK web server in another terminal:")
        click.echo(click.style(f"    adk web --port 8000", fg="cyan"))
        click.echo()
        click.echo("  This enables full ADK debugging at http://localhost:8000")
        click.echo()

    # Register with PocketNode
    click.echo(f"\nRegistering with {sdk.config.pocketnode_url}...")
    await sdk.discover(dir)

    if not sdk.runners:
        raise click.ClickException(
            "No agents could be registered!\n"
            "Check that your SDK token is valid."
        )

    # Run
    click.echo(f"\nConnecting to {sdk.config.server}")
    click.echo(f"Workspace: {sdk.config.workspace}")
    click.echo(f"ADK Server: {adk_url}")
    click.echo(f"Agents: {', '.join(f'@{r.agent.handle}' for r in sdk.runners)}")
    click.echo()
    click.echo(click.style("Debug your agents at: ", fg="white") + click.style(adk_url, fg="cyan"))
    click.echo()

    await sdk.run()


@cli.command()
@click.option(
    "--dir", "-d",
    default=".",
    help="Directory to search for agents"
)
def discover(dir: str):
    """Discover agents in a directory (without connecting)"""
    agents = discover_agents(dir)

    if not agents:
        click.echo("No agents found.")
        click.echo(f"\nSearched in: {Path(dir).resolve()}")
        return

    click.echo(f"Found {len(agents)} agent(s):\n")
    for agent in agents:
        click.echo(f"  @{agent.handle}")
        click.echo(f"    Path: {agent.path}")
        click.echo(f"    Agent: {type(agent.root_agent).__name__}")
        click.echo()


def main():
    cli()


if __name__ == "__main__":
    main()
