"""Third-party provider commands (Unusual Whales, Massive)."""

from __future__ import annotations

import click


# ---------------------------------------------------------------------------
# Top-level group
# ---------------------------------------------------------------------------

@click.group()
def providers():
    """Third-party data providers (Unusual Whales, Massive)."""
    pass


# ---------------------------------------------------------------------------
# Unusual Whales subgroup
# ---------------------------------------------------------------------------

@providers.group("uw")
def uw():
    """Unusual Whales: options flow, dark pool, Congress trades, and more."""
    pass


@uw.command("flow")
@click.option("--ticker", default=None, help="Filter by ticker symbol")
@click.option("--min-premium", type=int, default=None, help="Minimum premium in dollars")
@click.option("--sweep/--no-sweep", default=None, help="Filter sweep orders")
@click.option("--calls/--no-calls", default=None, help="Filter calls")
@click.option("--puts/--no-puts", default=None, help="Filter puts")
@click.option("--otm/--no-otm", default=None, help="Filter out-of-the-money")
@click.option("--min-dte", type=int, default=None, help="Minimum days to expiry")
@click.option("--max-dte", type=int, default=None, help="Maximum days to expiry")
@click.option("--limit", type=int, default=50, help="Number of results")
@click.pass_context
def uw_flow(ctx, ticker, min_premium, sweep, calls, puts, otm, min_dte, max_dte, limit):
    """Get unusual options flow alerts.

    Example: horizon providers uw flow --ticker AAPL --min-premium 100000
    """
    from horizon.provider_tools import uw_options_flow
    from horizon.cli._fmt import output

    result = uw_options_flow(
        ticker=ticker, min_premium=min_premium, is_sweep=sweep,
        is_call=calls, is_put=puts, is_otm=otm,
        min_dte=min_dte, max_dte=max_dte, limit=limit,
    )
    output(result, json_mode=ctx.obj.get("json", False))


@uw.command("stock-flow")
@click.argument("ticker")
@click.option("--side", default=None, help="Filter by side (call/put)")
@click.option("--min-premium", type=int, default=None, help="Minimum premium")
@click.pass_context
def uw_stock_flow(ctx, ticker, side, min_premium):
    """Get recent options flow for a specific ticker.

    Example: horizon providers uw stock-flow TSLA
    """
    from horizon.provider_tools import uw_stock_flow as _fn
    from horizon.cli._fmt import output

    output(_fn(ticker, side=side, min_premium=min_premium), json_mode=ctx.obj.get("json", False))


@uw.command("dark-pool")
@click.argument("ticker", required=False, default=None)
@click.option("--date", default=None, help="Filter by date (YYYY-MM-DD)")
@click.option("--min-size", type=int, default=None, help="Minimum trade size")
@click.option("--limit", type=int, default=50, help="Number of results")
@click.pass_context
def uw_dark_pool(ctx, ticker, date, min_size, limit):
    """Get dark pool trades (market-wide or per ticker).

    \b
    Examples:
      horizon providers uw dark-pool               # market-wide
      horizon providers uw dark-pool AAPL           # specific ticker
      horizon providers uw dark-pool NVDA --min-size 10000
    """
    from horizon.provider_tools import uw_dark_pool_recent, uw_dark_pool as _fn
    from horizon.cli._fmt import output

    if ticker:
        result = _fn(ticker, date=date, min_size=min_size, limit=limit)
    else:
        if date or min_size:
            click.echo("Warning: --date and --min-size require a ticker argument, ignoring.", err=True)
        result = uw_dark_pool_recent()
    output(result, json_mode=ctx.obj.get("json", False))


@uw.command("congress")
@click.option("--ticker", default=None, help="Filter by ticker")
@click.option("--name", default=None, help="Filter by Congress member name")
@click.option("--date", default=None, help="Filter by date (YYYY-MM-DD)")
@click.option("--limit", type=int, default=50, help="Number of results")
@click.pass_context
def uw_congress(ctx, ticker, name, date, limit):
    """Get Congress member stock trades.

    \b
    Examples:
      horizon providers uw congress
      horizon providers uw congress --ticker NVDA
      horizon providers uw congress --name "Pelosi"
    """
    from horizon.provider_tools import uw_congress_trades, uw_congress_trader
    from horizon.cli._fmt import output

    if name:
        if ticker or date:
            click.echo("Warning: --ticker and --date are ignored when --name is used.", err=True)
        result = uw_congress_trader(name)
    else:
        result = uw_congress_trades(limit=limit, ticker=ticker, date=date)
    output(result, json_mode=ctx.obj.get("json", False))


@uw.command("insiders")
@click.option("--ticker", default=None, help="Filter by ticker")
@click.option("--min-value", type=int, default=None, help="Minimum transaction value")
@click.option("--officer/--no-officer", default=None, help="Filter officers")
@click.option("--director/--no-director", default=None, help="Filter directors")
@click.option("--ten-percent-owner/--no-ten-percent-owner", default=None, help="Filter 10%+ owners")
@click.option("--start-date", default=None, help="Start date (YYYY-MM-DD)")
@click.option("--end-date", default=None, help="End date (YYYY-MM-DD)")
@click.option("--limit", type=int, default=50, help="Number of results")
@click.pass_context
def uw_insiders(ctx, ticker, min_value, officer, director, ten_percent_owner, start_date, end_date, limit):
    """Get insider transactions (Form 4 filings).

    Example: horizon providers uw insiders --ticker AAPL --min-value 1000000
    """
    from horizon.provider_tools import uw_insider_trades
    from horizon.cli._fmt import output

    result = uw_insider_trades(
        ticker=ticker, min_value=min_value,
        is_officer=officer, is_director=director,
        is_ten_percent_owner=ten_percent_owner,
        start_date=start_date, end_date=end_date, limit=limit,
    )
    output(result, json_mode=ctx.obj.get("json", False))


@uw.command("tide")
@click.option("--date", default=None, help="Date (YYYY-MM-DD)")
@click.option("--otm/--no-otm", default=None, help="Filter OTM only")
@click.pass_context
def uw_tide(ctx, date, otm):
    """Get Market Tide sentiment indicator.

    Example: horizon providers uw tide
    """
    from horizon.provider_tools import uw_market_tide
    from horizon.cli._fmt import output

    output(uw_market_tide(date=date, otm_only=otm), json_mode=ctx.obj.get("json", False))


@uw.command("spike")
@click.pass_context
def uw_spike(ctx):
    """Get SPIKE volatility indicator."""
    from horizon.provider_tools import uw_spike as _fn
    from horizon.cli._fmt import output

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


@uw.command("stock")
@click.argument("ticker")
@click.pass_context
def uw_stock(ctx, ticker):
    """Get stock information and current state.

    Example: horizon providers uw stock AAPL
    """
    from horizon.provider_tools import uw_stock_info
    from horizon.cli._fmt import output

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


@uw.command("greeks")
@click.argument("ticker")
@click.option("--by-strike", is_flag=True, help="Break down by strike")
@click.option("--by-expiry", is_flag=True, help="Break down by expiry")
@click.pass_context
def uw_greeks(ctx, ticker, by_strike, by_expiry):
    """Get Greek exposure (GEX, DEX) for a ticker.

    \b
    Examples:
      horizon providers uw greeks SPY
      horizon providers uw greeks SPY --by-strike
      horizon providers uw greeks SPY --by-expiry
    """
    from horizon.provider_tools import uw_greek_exposure, uw_greek_exposure_by_strike, uw_greek_exposure_by_expiry
    from horizon.cli._fmt import output

    if by_strike and by_expiry:
        click.echo("Error: --by-strike and --by-expiry are mutually exclusive.", err=True)
        return
    if by_strike:
        result = uw_greek_exposure_by_strike(ticker)
    elif by_expiry:
        result = uw_greek_exposure_by_expiry(ticker)
    else:
        result = uw_greek_exposure(ticker)
    output(result, json_mode=ctx.obj.get("json", False))


@uw.command("iv")
@click.argument("ticker")
@click.pass_context
def uw_iv(ctx, ticker):
    """Get IV rank percentile for a ticker.

    Example: horizon providers uw iv TSLA
    """
    from horizon.provider_tools import uw_iv_rank
    from horizon.cli._fmt import output

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


@uw.command("shorts")
@click.argument("ticker")
@click.pass_context
def uw_shorts(ctx, ticker):
    """Get short interest and float data.

    Example: horizon providers uw shorts GME
    """
    from horizon.provider_tools import uw_short_interest
    from horizon.cli._fmt import output

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


@uw.command("max-pain")
@click.argument("ticker")
@click.pass_context
def uw_max_pain(ctx, ticker):
    """Get max pain levels for a ticker.

    Example: horizon providers uw max-pain SPY
    """
    from horizon.provider_tools import uw_max_pain as _fn
    from horizon.cli._fmt import output

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


@uw.command("screener")
@click.option("--type", "stype", type=click.Choice(["stocks", "options"]), default="stocks")
@click.option("--min-premium", type=int, default=None, help="Min premium (options)")
@click.option("--otm/--no-otm", default=None, help="Filter OTM (options only)")
@click.option("--min-vol-oi", type=float, default=None, help="Min volume/OI ratio (options only)")
@click.option("--limit", type=int, default=50, help="Number of results")
@click.pass_context
def uw_screener(ctx, stype, min_premium, otm, min_vol_oi, limit):
    """Screen stocks or option chains.

    \b
    Examples:
      horizon providers uw screener --type stocks
      horizon providers uw screener --type options --min-premium 500000
      horizon providers uw screener --type options --min-vol-oi 2.0
    """
    from horizon.provider_tools import uw_screener_stocks, uw_screener_options
    from horizon.cli._fmt import output

    if stype == "options":
        result = uw_screener_options(limit=limit, min_premium=min_premium, is_otm=otm, min_volume_oi_ratio=min_vol_oi)
    else:
        result = uw_screener_stocks()
    output(result, json_mode=ctx.obj.get("json", False))


@uw.command("earnings")
@click.argument("ticker", required=False, default=None)
@click.option("--schedule", type=click.Choice(["premarket", "afterhours"]), default=None, help="Show earnings schedule instead")
@click.pass_context
def uw_earnings(ctx, ticker, schedule):
    """Get earnings history or upcoming schedule.

    \b
    Examples:
      horizon providers uw earnings AAPL           # history
      horizon providers uw earnings --schedule premarket  # upcoming
    """
    from horizon.provider_tools import uw_earnings as _fn, uw_earnings_schedule
    from horizon.cli._fmt import output

    if schedule:
        result = uw_earnings_schedule(schedule)
    elif ticker:
        result = _fn(ticker)
    else:
        result = uw_earnings_schedule("premarket")
    output(result, json_mode=ctx.obj.get("json", False))


@uw.command("calendar")
@click.option("--type", "ctype", type=click.Choice(["economic", "fda"]), default="economic")
@click.pass_context
def uw_calendar(ctx, ctype):
    """Get economic or FDA calendar.

    Example: horizon providers uw calendar --type economic
    """
    from horizon.provider_tools import uw_economic_calendar, uw_fda_calendar
    from horizon.cli._fmt import output

    result = uw_economic_calendar() if ctype == "economic" else uw_fda_calendar()
    output(result, json_mode=ctx.obj.get("json", False))


@uw.command("news")
@click.pass_context
def uw_news(ctx):
    """Get financial news headlines."""
    from horizon.provider_tools import uw_news as _fn
    from horizon.cli._fmt import output

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


@uw.command("predictions")
@click.option("--type", "ptype", type=click.Choice(["whales", "unusual"]), default="unusual")
@click.pass_context
def uw_predictions(ctx, ptype):
    """Get prediction market whales or unusual activity.

    Example: horizon providers uw predictions --type whales
    """
    from horizon.provider_tools import uw_prediction_whales, uw_prediction_unusual
    from horizon.cli._fmt import output

    result = uw_prediction_whales() if ptype == "whales" else uw_prediction_unusual()
    output(result, json_mode=ctx.obj.get("json", False))


@uw.command("vol-term")
@click.argument("ticker")
@click.pass_context
def uw_vol_term(ctx, ticker):
    """Get IV term structure across expirations.

    Example: horizon providers uw vol-term TSLA
    """
    from horizon.provider_tools import uw_vol_term_structure
    from horizon.cli._fmt import output

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


@uw.command("option-chains")
@click.argument("ticker")
@click.pass_context
def uw_option_chains_cmd(ctx, ticker):
    """Get full option chains for a ticker.

    Example: horizon providers uw option-chains SPY
    """
    from horizon.provider_tools import uw_option_chains
    from horizon.cli._fmt import output

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


@uw.command("short-volume")
@click.argument("ticker")
@click.pass_context
def uw_short_volume(ctx, ticker):
    """Get short volume and ratio history.

    Example: horizon providers uw short-volume GME
    """
    from horizon.provider_tools import uw_short_volume as _fn
    from horizon.cli._fmt import output

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


@uw.command("ftd")
@click.argument("ticker")
@click.pass_context
def uw_ftd(ctx, ticker):
    """Get failures to deliver for a ticker.

    Example: horizon providers uw ftd AMC
    """
    from horizon.provider_tools import uw_ftd as _fn
    from horizon.cli._fmt import output

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


@uw.command("etf-holdings")
@click.argument("ticker")
@click.pass_context
def uw_etf_holdings(ctx, ticker):
    """Get ETF holdings breakdown.

    Example: horizon providers uw etf-holdings SPY
    """
    from horizon.provider_tools import uw_etf_holdings as _fn
    from horizon.cli._fmt import output

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


@uw.command("etf-flow")
@click.argument("ticker")
@click.pass_context
def uw_etf_flow(ctx, ticker):
    """Get ETF inflow/outflow data.

    Example: horizon providers uw etf-flow QQQ
    """
    from horizon.provider_tools import uw_etf_flow as _fn
    from horizon.cli._fmt import output

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


@uw.command("seasonality")
@click.argument("ticker")
@click.pass_context
def uw_seasonality(ctx, ticker):
    """Get monthly seasonality for a ticker.

    Example: horizon providers uw seasonality AAPL
    """
    from horizon.provider_tools import uw_seasonality as _fn
    from horizon.cli._fmt import output

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


@uw.command("crypto-whales")
@click.pass_context
def uw_crypto_whales(ctx):
    """Get recent crypto whale transactions."""
    from horizon.provider_tools import uw_crypto_whales as _fn
    from horizon.cli._fmt import output

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


@uw.command("institutions")
@click.option("--name", default=None, help="Get holdings for a specific institution")
@click.pass_context
def uw_institutions_cmd(ctx, name):
    """List tracked institutions or get holdings for one.

    \b
    Examples:
      horizon providers uw institutions
      horizon providers uw institutions --name "Berkshire Hathaway"
    """
    from horizon.provider_tools import uw_institutions as _list, uw_institution_holdings
    from horizon.cli._fmt import output

    if name:
        result = uw_institution_holdings(name)
    else:
        result = _list()
    output(result, json_mode=ctx.obj.get("json", False))


@uw.command("ownership")
@click.argument("ticker")
@click.pass_context
def uw_ownership(ctx, ticker):
    """Get institutional ownership of a ticker.

    Example: horizon providers uw ownership AAPL
    """
    from horizon.provider_tools import uw_institution_ownership
    from horizon.cli._fmt import output

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


@uw.command("stock-state")
@click.argument("ticker")
@click.pass_context
def uw_stock_state(ctx, ticker):
    """Get current stock state.

    Example: horizon providers uw stock-state AAPL
    """
    from horizon.provider_tools import uw_stock_state as _fn
    from horizon.cli._fmt import output

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


# ---------------------------------------------------------------------------
# Massive (Polygon.io) subgroup
# ---------------------------------------------------------------------------

@providers.group("massive")
def massive():
    """Massive (Polygon.io): market data, snapshots, options, technicals."""
    pass


@massive.command("bars")
@click.argument("ticker")
@click.option("--from", "from_date", required=True, help="Start date (YYYY-MM-DD)")
@click.option("--to", "to_date", required=True, help="End date (YYYY-MM-DD)")
@click.option("--timespan", type=click.Choice(["second", "minute", "hour", "day", "week", "month", "quarter", "year"]), default="day", help="Bar timespan")
@click.option("--multiplier", type=int, default=1, help="Timespan multiplier")
@click.option("--limit", type=int, default=5000, help="Max bars")
@click.pass_context
def massive_bars(ctx, ticker, from_date, to_date, timespan, multiplier, limit):
    """Get OHLCV bars for a ticker.

    Example: horizon providers massive bars AAPL --from 2024-01-01 --to 2024-06-30
    """
    from horizon.provider_tools import massive_aggregates
    from horizon.cli._fmt import output

    result = massive_aggregates(ticker, multiplier, timespan, from_date, to_date, limit=limit)
    output(result, json_mode=ctx.obj.get("json", False))


@massive.command("snapshot")
@click.argument("ticker")
@click.pass_context
def massive_snap(ctx, ticker):
    """Get real-time snapshot for a ticker.

    Example: horizon providers massive snapshot AAPL
    """
    from horizon.provider_tools import massive_snapshot
    from horizon.cli._fmt import output

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


@massive.command("movers")
@click.option("--direction", type=click.Choice(["gainers", "losers"]), default="gainers")
@click.pass_context
def massive_movers(ctx, direction):
    """Get top 20 gainers or losers.

    Example: horizon providers massive movers --direction losers
    """
    from horizon.provider_tools import massive_gainers_losers
    from horizon.cli._fmt import output

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


@massive.command("quote")
@click.argument("ticker")
@click.pass_context
def massive_quote(ctx, ticker):
    """Get last trade and NBBO quote.

    Example: horizon providers massive quote TSLA
    """
    from horizon.provider_tools import massive_last_trade, massive_last_quote
    from horizon.cli._fmt import output

    trade = massive_last_trade(ticker)
    quote = massive_last_quote(ticker)
    output({"last_trade": trade, "last_quote": quote}, json_mode=ctx.obj.get("json", False))


@massive.command("details")
@click.argument("ticker")
@click.pass_context
def massive_details(ctx, ticker):
    """Get ticker details: name, market cap, sector, description.

    Example: horizon providers massive details NVDA
    """
    from horizon.provider_tools import massive_ticker_details
    from horizon.cli._fmt import output

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


@massive.command("search")
@click.argument("query")
@click.option("--market", default=None, help="stocks/crypto/fx/otc")
@click.option("--limit", type=int, default=20, help="Number of results")
@click.pass_context
def massive_search(ctx, query, market, limit):
    """Search tickers by name or symbol.

    Example: horizon providers massive search "apple" --market stocks
    """
    from horizon.provider_tools import massive_search_tickers
    from horizon.cli._fmt import output

    output(massive_search_tickers(query, market=market, limit=limit), json_mode=ctx.obj.get("json", False))


@massive.command("status")
@click.pass_context
def massive_status(ctx):
    """Get current market status (open/closed/early hours)."""
    from horizon.provider_tools import massive_market_status
    from horizon.cli._fmt import output

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


@massive.command("options")
@click.argument("underlying")
@click.option("--type", "contract_type", default=None, help="call or put")
@click.option("--expiry", default=None, help="Expiration date (YYYY-MM-DD)")
@click.option("--expiry-gte", default=None, help="Expiry on or after (YYYY-MM-DD)")
@click.option("--strike-gte", type=float, default=None, help="Min strike price")
@click.option("--strike-lte", type=float, default=None, help="Max strike price")
@click.option("--limit", type=int, default=250, help="Max contracts")
@click.pass_context
def massive_options(ctx, underlying, contract_type, expiry, expiry_gte, strike_gte, strike_lte, limit):
    """Get options chain with Greeks for an underlying.

    \b
    Examples:
      horizon providers massive options AAPL --type call --expiry 2024-06-21
      horizon providers massive options SPY --expiry-gte 2024-07-01
    """
    from horizon.provider_tools import massive_options_chain
    from horizon.cli._fmt import output

    result = massive_options_chain(
        underlying,
        contract_type=contract_type, expiration_date=expiry,
        expiration_date_gte=expiry_gte,
        strike_price_gte=strike_gte, strike_price_lte=strike_lte,
        limit=limit,
    )
    output(result, json_mode=ctx.obj.get("json", False))


@massive.command("sma")
@click.argument("ticker")
@click.option("--window", type=int, default=50, help="Window size")
@click.option("--timespan", type=click.Choice(["second", "minute", "hour", "day", "week", "month"]), default="day", help="Timespan")
@click.option("--limit", type=int, default=50, help="Number of values")
@click.pass_context
def massive_sma_cmd(ctx, ticker, window, timespan, limit):
    """Get Simple Moving Average.

    Example: horizon providers massive sma AAPL --window 200
    """
    from horizon.provider_tools import massive_sma
    from horizon.cli._fmt import output

    output(massive_sma(ticker, timespan=timespan, window=window, limit=limit), json_mode=ctx.obj.get("json", False))


@massive.command("rsi")
@click.argument("ticker")
@click.option("--window", type=int, default=14, help="Window size")
@click.option("--timespan", type=click.Choice(["second", "minute", "hour", "day", "week", "month"]), default="day", help="Timespan")
@click.option("--limit", type=int, default=50, help="Number of values")
@click.pass_context
def massive_rsi_cmd(ctx, ticker, window, timespan, limit):
    """Get Relative Strength Index.

    Example: horizon providers massive rsi TSLA --window 14
    """
    from horizon.provider_tools import massive_rsi
    from horizon.cli._fmt import output

    output(massive_rsi(ticker, timespan=timespan, window=window, limit=limit), json_mode=ctx.obj.get("json", False))


@massive.command("macd")
@click.argument("ticker")
@click.option("--timespan", type=click.Choice(["second", "minute", "hour", "day", "week", "month"]), default="day", help="Timespan")
@click.option("--limit", type=int, default=50, help="Number of values")
@click.pass_context
def massive_macd_cmd(ctx, ticker, timespan, limit):
    """Get MACD indicator.

    Example: horizon providers massive macd AAPL
    """
    from horizon.provider_tools import massive_macd
    from horizon.cli._fmt import output

    output(massive_macd(ticker, timespan=timespan, limit=limit), json_mode=ctx.obj.get("json", False))


@massive.command("news")
@click.option("--ticker", default=None, help="Filter by ticker")
@click.option("--limit", type=int, default=20, help="Number of articles")
@click.pass_context
def massive_news_cmd(ctx, ticker, limit):
    """Get market news, optionally filtered by ticker.

    Example: horizon providers massive news --ticker AAPL
    """
    from horizon.provider_tools import massive_news
    from horizon.cli._fmt import output

    output(massive_news(ticker=ticker, limit=limit), json_mode=ctx.obj.get("json", False))


@massive.command("dividends")
@click.argument("ticker")
@click.option("--limit", type=int, default=20, help="Number of results")
@click.pass_context
def massive_divs(ctx, ticker, limit):
    """Get dividend history for a ticker.

    Example: horizon providers massive dividends AAPL
    """
    from horizon.provider_tools import massive_dividends
    from horizon.cli._fmt import output

    output(massive_dividends(ticker, limit=limit), json_mode=ctx.obj.get("json", False))


@massive.command("crypto")
@click.argument("ticker")
@click.pass_context
def massive_crypto(ctx, ticker):
    """Get crypto snapshot (use X:BTCUSD format).

    Example: horizon providers massive crypto X:BTCUSD
    """
    from horizon.provider_tools import massive_crypto_snapshot
    from horizon.cli._fmt import output

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


@massive.command("forex")
@click.argument("from_currency")
@click.argument("to_currency")
@click.pass_context
def massive_forex(ctx, from_currency, to_currency):
    """Get real-time forex conversion rate.

    Example: horizon providers massive forex EUR USD
    """
    from horizon.provider_tools import massive_forex_conversion
    from horizon.cli._fmt import output

    output(massive_forex_conversion(from_currency, to_currency), json_mode=ctx.obj.get("json", False))


@massive.command("ema")
@click.argument("ticker")
@click.option("--window", type=int, default=50, help="Window size")
@click.option("--timespan", type=click.Choice(["second", "minute", "hour", "day", "week", "month"]), default="day", help="Timespan")
@click.option("--limit", type=int, default=50, help="Number of values")
@click.pass_context
def massive_ema_cmd(ctx, ticker, window, timespan, limit):
    """Get Exponential Moving Average.

    Example: horizon providers massive ema AAPL --window 20
    """
    from horizon.provider_tools import massive_ema
    from horizon.cli._fmt import output

    output(massive_ema(ticker, timespan=timespan, window=window, limit=limit), json_mode=ctx.obj.get("json", False))


@massive.command("splits")
@click.argument("ticker")
@click.option("--limit", type=int, default=20, help="Number of results")
@click.pass_context
def massive_splits_cmd(ctx, ticker, limit):
    """Get stock split history.

    Example: horizon providers massive splits TSLA
    """
    from horizon.provider_tools import massive_splits
    from horizon.cli._fmt import output

    output(massive_splits(ticker, limit=limit), json_mode=ctx.obj.get("json", False))


@massive.command("prev-close")
@click.argument("ticker")
@click.pass_context
def massive_prev_close(ctx, ticker):
    """Get previous day's OHLCV.

    Example: horizon providers massive prev-close AAPL
    """
    from horizon.provider_tools import massive_previous_close
    from horizon.cli._fmt import output

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


@massive.command("holidays")
@click.pass_context
def massive_holidays(ctx):
    """Get upcoming market holidays."""
    from horizon.provider_tools import massive_market_holidays
    from horizon.cli._fmt import output

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


@massive.command("contracts")
@click.option("--underlying", default=None, help="Underlying ticker")
@click.option("--type", "contract_type", default=None, help="call or put")
@click.option("--expiry", default=None, help="Expiration date (YYYY-MM-DD)")
@click.option("--strike", type=float, default=None, help="Strike price")
@click.option("--limit", type=int, default=100, help="Max results")
@click.pass_context
def massive_contracts(ctx, underlying, contract_type, expiry, strike, limit):
    """List options contracts with filters.

    Example: horizon providers massive contracts --underlying AAPL --type call
    """
    from horizon.provider_tools import massive_options_contracts
    from horizon.cli._fmt import output

    result = massive_options_contracts(
        underlying_ticker=underlying, contract_type=contract_type,
        expiration_date=expiry, strike_price=strike, limit=limit,
    )
    output(result, json_mode=ctx.obj.get("json", False))


@massive.command("crypto-movers")
@click.option("--direction", type=click.Choice(["gainers", "losers"]), default="gainers")
@click.pass_context
def massive_crypto_movers(ctx, direction):
    """Get top crypto gainers or losers.

    Example: horizon providers massive crypto-movers --direction losers
    """
    from horizon.provider_tools import massive_crypto_gainers_losers
    from horizon.cli._fmt import output

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


@massive.command("forex-snapshot")
@click.argument("ticker")
@click.pass_context
def massive_forex_snap(ctx, ticker):
    """Get forex pair snapshot (use C:EURUSD format).

    Example: horizon providers massive forex-snapshot C:EURUSD
    """
    from horizon.provider_tools import massive_forex_snapshot
    from horizon.cli._fmt import output

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


@massive.command("grouped")
@click.argument("date")
@click.option("--adjusted/--no-adjusted", default=True, help="Adjusted for splits")
@click.pass_context
def massive_grouped(ctx, date, adjusted):
    """Get OHLCV for the entire market on a date.

    Example: horizon providers massive grouped 2024-06-14
    """
    from horizon.provider_tools import massive_grouped_daily
    from horizon.cli._fmt import output

    output(massive_grouped_daily(date, adjusted=adjusted), json_mode=ctx.obj.get("json", False))
