"""CLI entry point."""
import click, logging, requests
from localrun import __version__

LOGO = """
\033[36m
    __    ____  _________    __    ____  __  ___   __
   / /   / __ \/ ____/   |  / /   / __ \/ / / / | / /
  / /   / / / / /   / /| | / /   / /_/ / / / /  |/ / 
 / /___/ /_/ / /___/ ___ |/ /___/ _, _/ /_/ / /|  /  
/_____/\____/\____/_/  |_/_____/_/ |_|\____/_/ |_/ 
\033[0m"""

MENU = f"""{LOGO}
\033[90m  AWS Local Emulator  v{__version__}\033[0m

  \033[1mUsage:\033[0m  aws-local-run <command> [options]

  \033[1mCommands:\033[0m
    \033[32mstart\033[0m       Start the LocalRun server
    \033[32mstatus\033[0m      Check if LocalRun is running
    \033[32mservices\033[0m    List all supported AWS services
    \033[32m--version\033[0m   Show version
    \033[32m--help\033[0m      Show this message

  \033[1mQuick start:\033[0m
    \033[90m$\033[0m aws-local-run start
    \033[90m$\033[0m aws-local-run start --port 5000 --services s3,sqs,dynamodb
    \033[90m$\033[0m aws-local-run status
"""

@click.group(invoke_without_command=True)
@click.version_option(__version__, prog_name="aws-local-run")
@click.pass_context
def main(ctx):
    """LocalRun — run AWS services locally."""
    if ctx.invoked_subcommand is None:
        click.echo(MENU)

@main.command()
@click.option("--port", default=4566, help="Port to listen on")
@click.option("--host", default="0.0.0.0", help="Host to bind to")
@click.option("--services", default=None, help="Comma-separated service list")
@click.option("--data-dir", default=None, help="Data persistence directory")
@click.option("--debug", is_flag=True, help="Enable debug logging")
def start(port, host, services, data_dir, debug):
    """Start the LocalRun server."""
    from localrun.config import LocalRunConfig, set_config
    from localrun.gateway import create_app

    level = logging.DEBUG if debug else logging.INFO
    logging.basicConfig(level=level, format="%(levelname)s %(name)s: %(message)s")

    config = LocalRunConfig(host=host, port=port, debug=debug)
    if services:
        for s in ["s3","sqs","dynamodb","sns","lambda","iam","logs","sts","secretsmanager","ssm","events","cloudformation","rds","apigateway"]:
            config.enabled_services[s] = False
        for s in services.split(","):
            config.enabled_services[s.strip()] = True
    if data_dir:
        config.data_dir = data_dir
    set_config(config)

    click.echo(LOGO)
    svc_list = ", ".join(s for s, on in config.enabled_services.items() if on)
    click.echo(f"  \033[90mAWS Local Emulator  v{__version__}\033[0m\n")
    click.echo(f"  \033[32m➜\033[0m  http://{host}:{port}")
    click.echo(f"  \033[32m➜\033[0m  Services: {svc_list}\n")

    app = create_app()
    app.run(host=host, port=port, debug=debug, use_reloader=False)

@main.command()
@click.option("--port", default=4566)
def status(port):
    """Check if LocalRun is running."""
    try:
        r = requests.get(f"http://localhost:{port}/health", timeout=2)
        click.echo(f"\033[32m✔\033[0m LocalRun is running (status {r.status_code})")
    except Exception:
        click.echo(f"\033[31m✖\033[0m LocalRun is not running on port {port}")

@main.command()
def services():
    """List all supported AWS services."""
    click.echo(LOGO)
    click.echo(f"  \033[90mAWS Local Emulator  v{__version__}\033[0m\n")
    click.echo("  \033[1mSupported Services (14):\033[0m\n")
    all_svc = [
        ("s3",             "Buckets, objects, copy, multi-delete"),
        ("sqs",            "Queues, messages, purge, attributes"),
        ("dynamodb",       "Tables, items, query, scan, batch ops"),
        ("sns",            "Topics, subscriptions, publish"),
        ("lambda",         "Functions, invoke via subprocess"),
        ("iam",            "Roles, policies, users (stub)"),
        ("logs",           "Log groups, streams, events"),
        ("sts",            "GetCallerIdentity, AssumeRole"),
        ("secretsmanager", "Secrets CRUD, versioning, tags"),
        ("ssm",            "Parameters CRUD, get-by-path"),
        ("events",         "Rules, targets, event buses"),
        ("cloudformation", "Stacks CRUD, templates (stub)"),
        ("rds",            "DB instances, clusters (stub)"),
        ("apigateway",     "REST APIs, resources, stages"),
    ]
    for name, desc in all_svc:
        click.echo(f"    \033[32m•\033[0m {name:<18} \033[90m{desc}\033[0m")
    click.echo()
