"""CLI commands for metrics server."""

from __future__ import annotations

import logging
import time

import click

from oclawma.cli_ui import (
    accent,
    header,
    key_value,
    print_error,
    print_info,
    print_success,
    subheader,
)
from oclawma.metrics import MetricsServer, TrackedJobQueue
from oclawma.metrics.collector import get_collector
from oclawma.queue import JobQueue

logger = logging.getLogger(__name__)


@click.command(name="metrics")
@click.option(
    "--port",
    "-p",
    type=int,
    default=9090,
    help="Port to listen on",
    show_default=True,
)
@click.option(
    "--host",
    "-h",
    default="0.0.0.0",
    help="Host address to bind to",
    show_default=True,
)
@click.option(
    "--queue-db",
    "-q",
    type=click.Path(exists=False),
    help="Path to queue database (default: in-memory)",
)
@click.option(
    "--collect-interval",
    "-i",
    type=float,
    default=10.0,
    help="Queue metrics collection interval in seconds",
    show_default=True,
)
def metrics_cli(
    port: int,
    host: str,
    queue_db: str | None,
    collect_interval: float,
) -> None:
    """Start metrics HTTP server for Prometheus scraping.

    Exposes job queue metrics in Prometheus-compatible format.

    Endpoints:
        /metrics       - Prometheus text format
        /metrics/json  - JSON format
        /health        - Health check

    Examples:
        oclawma metrics                    # Start on default port 9090
        oclawma metrics -p 8080            # Start on port 8080
        oclawma metrics -q /path/to/db     # Connect to queue database
        oclawma metrics -h 127.0.0.1       # Bind to localhost only
    """
    click.echo(header("METRICS SERVER", width=58))
    click.echo()

    # Create or get global collector
    collector = get_collector()

    # Set up queue integration if database path provided
    tracked_queue: TrackedJobQueue | None = None
    queue: JobQueue | None = None

    if queue_db:
        click.echo(subheader("QUEUE CONFIGURATION"))
        click.echo(key_value("Database", queue_db))
        click.echo(key_value("Collect Interval", f"{collect_interval}s"))
        click.echo()

        try:
            queue = JobQueue(queue_db)
            tracked_queue = TrackedJobQueue(queue, collector)
            print_success("Connected to queue database")
        except Exception as e:
            print_error(f"Failed to connect to queue: {e}")
            raise click.Abort() from None
    else:
        print_info("No queue database specified - metrics will start empty")

    # Create and start server
    click.echo(subheader("SERVER CONFIGURATION"))
    click.echo(key_value("Host", host))
    click.echo(key_value("Port", str(port)))
    click.echo()

    server = MetricsServer(collector, host=host, port=port)

    try:
        server.start()
        actual_port = server.port

        if actual_port != port:
            print_info(f"Port {port} was in use, using port {actual_port} instead")

        print_success(f"Metrics server started on {host}:{actual_port}")
        click.echo()

        # Show endpoints
        click.echo(subheader("ENDPOINTS"))
        base_url = f"http://{host}:{actual_port}"
        click.echo(f"  Prometheus: {accent(f'{base_url}/metrics')}")
        click.echo(f"  JSON:       {accent(f'{base_url}/metrics/json')}")
        click.echo(f"  Health:     {accent(f'{base_url}/health')}")
        click.echo()

        # Show example curl commands
        click.echo(subheader("EXAMPLE QUERIES"))
        click.echo(f"  curl {base_url}/metrics")
        click.echo(f"  curl {base_url}/metrics/json | jq")
        click.echo()

        # If we have a queue, start collection loop in background
        if tracked_queue:
            import threading

            def collect_loop():
                while True:
                    try:
                        collector.collect_from_queue(tracked_queue)
                    except Exception as e:
                        logger.warning(f"Metrics collection error: {e}")
                    time.sleep(collect_interval)

            collector_thread = threading.Thread(target=collect_loop, daemon=True)
            collector_thread.start()
            print_info(f"Background metrics collection started ({collect_interval}s interval)")
            click.echo()

        # Show initial metrics
        click.echo(subheader("INITIAL METRICS"))
        snapshot = collector.get_metrics_snapshot()
        click.echo(key_value("Jobs Processed", str(snapshot["jobs_processed"])))
        click.echo(key_value("Jobs Completed", str(snapshot["jobs_completed"])))
        click.echo(key_value("Jobs Failed", str(snapshot["jobs_failed"])))
        click.echo(key_value("Queue Depth", str(snapshot["queue_depth"])))
        click.echo()

        # Keep running until interrupted
        click.echo(subheader("STATUS"))
        click.echo("Press Ctrl+C to stop the server")
        click.echo()

        try:
            while server.is_running:
                time.sleep(1)
        except KeyboardInterrupt:
            click.echo()
            print_info("Shutdown requested...")
    finally:
        server.stop()
        if queue:
            queue.close()
        print_success("Server stopped")
