"""
CLI entry point for gcplocal.

Usage:
    gcplocal start [--host HOST] [--port PORT] [--debug]
    gcplocal terraform-config [--host HOST] [--port PORT] [--project PROJECT]
    gcplocal status
    gcplocal reset
"""

import json
import logging
import sys

import click

from gcplocal.constants import (
    DEFAULT_HOST,
    DEFAULT_PORT,
    DEFAULT_PROJECT,
    COMPUTE_API_PREFIX,
    STORAGE_API_PREFIX,
    IAM_API_PREFIX,
    PUBSUB_API_PREFIX,
    CRM_API_PREFIX,
    SQLADMIN_API_PREFIX,
)


@click.group()
@click.version_option(package_name="gcplocal")
def main():
    """gcplocal — Local GCP emulator for development and Terraform testing."""
    pass


@main.command()
@click.option("--host", default=DEFAULT_HOST, help="Bind address")
@click.option("--port", default=DEFAULT_PORT, type=int, help="Port number")
@click.option("--debug", is_flag=True, help="Enable Flask debug mode")
def start(host, port, debug):
    """Start the gcplocal emulator server."""
    logging.basicConfig(
        level=logging.DEBUG if debug else logging.INFO,
        format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
    )
    click.echo(f"""
╔══════════════════════════════════════════════════╗
║             gcplocal — GCP Emulator              ║
╠══════════════════════════════════════════════════╣
║  Listening on: http://{host}:{port:<5}               ║
║                                                  ║
║  Services:                                       ║
║    • Compute Engine    {COMPUTE_API_PREFIX:<27}║
║    • Cloud Storage     {STORAGE_API_PREFIX:<27}║
║    • IAM               {IAM_API_PREFIX:<27}║
║    • Pub/Sub           {PUBSUB_API_PREFIX:<27}║
║    • Resource Manager  {CRM_API_PREFIX:<27}║
║    • Cloud SQL         {SQLADMIN_API_PREFIX:<27}║
║                                                  ║
║  Run `gcplocal terraform-config` for TF setup    ║
╚══════════════════════════════════════════════════╝
""")
    from gcplocal.server import start_server
    start_server(host=host, port=port, debug=debug)


@main.command("terraform-config")
@click.option("--host", default="localhost", help="Server host")
@click.option("--port", default=DEFAULT_PORT, type=int, help="Server port")
@click.option("--project", default=DEFAULT_PROJECT, help="GCP project ID to use")
@click.option("--format", "fmt", type=click.Choice(["hcl", "json", "env"]), default="hcl")
def terraform_config(host, port, project, fmt):
    """Generate Terraform provider configuration for gcplocal."""
    base = f"http://{host}:{port}"

    endpoints = {
        "compute_custom_endpoint": f"{base}{COMPUTE_API_PREFIX}/",
        "storage_custom_endpoint": f"{base}{STORAGE_API_PREFIX}/",
        "iam_custom_endpoint": f"{base}{IAM_API_PREFIX}/",
        "pubsub_custom_endpoint": f"{base}{PUBSUB_API_PREFIX}/",
        "cloud_resource_manager_custom_endpoint": f"{base}{CRM_API_PREFIX}/",
        "sql_custom_endpoint": f"{base}{SQLADMIN_API_PREFIX}/",
    }

    if fmt == "hcl":
        click.echo('provider "google" {')
        click.echo(f'  project = "{project}"')
        click.echo(f'  region  = "us-central1"')
        click.echo()
        click.echo('  # Point all services at gcplocal')
        for key, val in endpoints.items():
            click.echo(f'  {key:<46} = "{val}"')
        click.echo()
        click.echo("  # Skip real auth — gcplocal accepts anything")
        click.echo('  access_token = "gcplocal-mock-token"')
        click.echo("}")

    elif fmt == "json":
        config = {
            "provider": {
                "google": {
                    "project": project,
                    "region": "us-central1",
                    "access_token": "gcplocal-mock-token",
                    **endpoints,
                }
            }
        }
        click.echo(json.dumps(config, indent=2))

    elif fmt == "env":
        click.echo("# Source these in your shell before running Terraform")
        for key, val in endpoints.items():
            env_key = f"GOOGLE_{key.upper()}"
            click.echo(f'export {env_key}="{val}"')
        click.echo(f'export GOOGLE_PROJECT="{project}"')


@main.command()
@click.option("--host", default="localhost")
@click.option("--port", default=DEFAULT_PORT, type=int)
def status(host, port):
    """Check if gcplocal is running."""
    import requests
    try:
        resp = requests.get(f"http://{host}:{port}/health", timeout=3)
        data = resp.json()
        click.echo(f"Status: {data.get('status', 'unknown')}")
        click.echo(f"Services: {', '.join(data.get('services', []))}")
        click.echo(f"Resources in memory: {data.get('resources_in_memory', 0)}")
    except Exception as e:
        click.echo(f"gcplocal is not running on {host}:{port} ({e})")
        sys.exit(1)


@main.command()
@click.option("--host", default="localhost")
@click.option("--port", default=DEFAULT_PORT, type=int)
def reset(host, port):
    """Reset all emulator state."""
    import requests
    try:
        resp = requests.post(f"http://{host}:{port}/reset", timeout=3)
        data = resp.json()
        click.echo(f"Reset: {data.get('message', 'done')}")
    except Exception as e:
        click.echo(f"Failed to reset: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
