"""Feed management commands."""

from __future__ import annotations

import click


@click.group()
def feed():
    """Feed management commands."""
    pass


@feed.command()
@click.argument("name")
@click.pass_context
def snapshot(ctx, name):
    """Get the latest snapshot for a feed.

    Example: horizon feed snapshot btc-price
    """
    from horizon.tools import get_feed_snapshot
    from horizon.cli._fmt import output

    output(get_feed_snapshot(name), json_mode=ctx.obj.get("json", False))


@feed.command("list")
@click.pass_context
def list_feeds(ctx):
    """List all active feeds with latest snapshots."""
    from horizon.tools import list_all_feeds
    from horizon.cli._fmt import output

    output(list_all_feeds(), json_mode=ctx.obj.get("json", False))


@feed.command()
@click.option("--threshold", default=30.0, help="Seconds before a feed is considered stale")
@click.pass_context
def health(ctx, threshold):
    """Check feed health and staleness."""
    from horizon.tools import check_feed_health
    from horizon.cli._fmt import output

    output(check_feed_health(stale_threshold=threshold), json_mode=ctx.obj.get("json", False))


@feed.command()
@click.argument("name")
@click.pass_context
def metrics(ctx, name):
    """Show connection metrics for a feed.

    Example: horizon feed metrics btc-price
    """
    from horizon.tools import feed_metrics
    from horizon.cli._fmt import output

    output(feed_metrics(name), json_mode=ctx.obj.get("json", False))


@feed.command("start")
@click.argument("name")
@click.argument("feed_type")
@click.option("--config", "config_json", default=None, help="JSON configuration string")
@click.option("--symbol", default=None, help="Symbol (for Binance feeds)")
@click.option("--url", default=None, help="Feed URL (for REST feeds)")
@click.option("--interval", default=5.0, type=float, help="Poll interval in seconds")
@click.pass_context
def start_feed(ctx, name, feed_type, config_json, symbol, url, interval):
    """Start a new data feed.

    \b
    Examples:
      horizon feed start btc-price binance_ws --symbol btcusdt
      horizon feed start my-feed rest --url https://api.example.com/price --interval 10
      horizon feed start espn-nba espn --config '{"sport":"basketball","league":"nba"}'
    """
    from horizon.tools import start_feed as _start_feed
    from horizon.cli._fmt import output

    result = _start_feed(
        name=name,
        feed_type=feed_type,
        config_json=config_json,
        symbol=symbol,
        url=url,
        interval=interval,
    )
    output(result, json_mode=ctx.obj.get("json", False))
