"""
Market Radar — a quick CLI dashboard.

Run:
    python market_radar.py

Prints trending markets, fastest-moving probabilities,
and markets closing soon.  Great for a morning briefing.
"""

import asyncio

from polymarket_client import get_markets
from analysis import (
    filter_closing_soon,
    format_market,
    rank_by_volume,
    safe_float,
)


def _pct(value: float) -> str:
    return f"{value * 100:.1f}%"


def _usd(value: float) -> str:
    if value >= 1_000_000:
        return f"${value / 1_000_000:.1f}M"
    if value >= 1_000:
        return f"${value / 1_000:.0f}K"
    return f"${value:.0f}"


async def radar() -> None:
    markets = await get_markets(limit=100, order="volume24hr")

    # ── 🔥 Trending ─────────────────────────────────────────────
    print("\n🔥  TRENDING MARKETS (by 24h volume)\n")
    for i, m in enumerate(rank_by_volume(markets, 10), 1):
        fm = format_market(m)
        print(
            f"  {i:>2}. {fm['question'][:70]}\n"
            f"      prob {_pct(fm['probability'])}  |  "
            f"vol {_usd(fm['volume_24h'])}  |  "
            f"liq {_usd(fm['liquidity'])}"
        )

    # ── ⚡ Fastest-moving probabilities ──────────────────────────
    print("\n⚡  HIGHEST LIQUIDITY MARKETS\n")
    by_liquidity = sorted(
        markets,
        key=lambda m: safe_float(m.get("liquidity")),
        reverse=True,
    )[:10]
    for i, m in enumerate(by_liquidity, 1):
        fm = format_market(m)
        print(
            f"  {i:>2}. {fm['question'][:70]}\n"
            f"      prob {_pct(fm['probability'])}  |  "
            f"liq {_usd(fm['liquidity'])}"
        )

    # ── ⏳ Closing soon ─────────────────────────────────────────
    all_markets = await get_markets(limit=100, order="endDate", ascending=True)
    closing = filter_closing_soon(all_markets, hours=48)
    print(f"\n⏳  MARKETS CLOSING WITHIN 48 HOURS ({len(closing)} found)\n")
    for i, m in enumerate(closing[:10], 1):
        fm = format_market(m)
        print(
            f"  {i:>2}. {fm['question'][:70]}\n"
            f"      prob {_pct(fm['probability'])}  |  "
            f"ends {fm['end_date'][:16]}"
        )

    print()


if __name__ == "__main__":
    asyncio.run(radar())
