"""Test all Fireplace SDK endpoints against the live API."""

import json
import os
import time
import traceback
from fireplace_gg import Fireplace

API_KEY = os.environ.get("FIREPLACE_API_KEY", "fp_pk_78263f02d30c478a4a3df446346b1afbaa47d3fd47687127")
API_SECRET = os.environ.get("FIREPLACE_API_SECRET", "fp_sk_17a5c86e81473e2566c8769b48de8dad818ef782b98c15ecc4105d0c287c432c")
TRADING_TOKEN = os.environ.get("FIREPLACE_TRADING_TOKEN", "")

fp = Fireplace(api_key=API_KEY, api_secret=API_SECRET, trading_token=TRADING_TOKEN or None)

MARKET_ID = "1473040"
EVENT_ID = "238474"
WALLET = "0x2eb5714ff6f20f5f9f7662c556dbef5e1c9bf4d4"

results = {}

def test(name, fn):
    """Run a test, print result, respect rate limits."""
    try:
        time.sleep(0.25)  # Rate limit: 5 req/s
        data = fn()
        # Truncate for display
        preview = json.dumps(data, default=str)[:200] if data else "None/empty"
        results[name] = "PASS"
        print(f"  PASS  {name}")
        print(f"         → {preview}")
    except Exception as e:
        results[name] = f"FAIL: {e}"
        print(f"  FAIL  {name}")
        print(f"         → {e}")

print("=" * 70)
print("FIREPLACE SDK v0.3.0 — ENDPOINT TESTS")
print("=" * 70)

# --- MARKETS ---
print("\n## Markets")
test("markets.get_by_id", lambda: fp.markets.get_by_id(MARKET_ID))
test("markets.get_event_by_id", lambda: fp.markets.get_event_by_id(EVENT_ID))
test("markets.overview", lambda: fp.markets.overview(MARKET_ID))  # NEW
test("markets.latest_candles", lambda: fp.markets.latest_candles(MARKET_ID))
test("markets.historical_candles", lambda: fp.markets.historical_candles(MARKET_ID, limit=5))  # PATH CHANGE
test("markets.recent_trades", lambda: fp.markets.recent_trades(MARKET_ID, limit=3))
test("markets.trades_summary", lambda: fp.markets.trades_summary(MARKET_ID))
test("markets.get_volume", lambda: fp.markets.get_volume(MARKET_ID))
test("markets.open_interest", lambda: fp.markets.open_interest(MARKET_ID))
test("markets.group_open_interest", lambda: fp.markets.group_open_interest(EVENT_ID))
test("markets.orderbook", lambda: fp.markets.orderbook(MARKET_ID))
test("markets.top_positions", lambda: fp.markets.top_positions(MARKET_ID, limit=3))
test("markets.top_positions_stats", lambda: fp.markets.top_positions_stats(MARKET_ID))
test("markets.top_positions_by_event", lambda: fp.markets.top_positions_by_event(EVENT_ID, limit=3))
test("markets.top_holders_stats", lambda: fp.markets.top_holders_stats(MARKET_ID, limit=3))
test("markets.unique_holders", lambda: fp.markets.unique_holders(MARKET_ID, limit=3, stats=True))  # UPDATED params
test("markets.holders_summary", lambda: fp.markets.holders_summary(MARKET_ID))

# --- PROFILES ---
print("\n## Profiles")
test("profiles.overview", lambda: fp.profiles.overview(WALLET))
test("profiles.positions", lambda: fp.profiles.positions(WALLET, limit=3))
test("profiles.recent_trades", lambda: fp.profiles.recent_trades(WALLET, limit=3))
test("profiles.recent_trades (date_from)", lambda: fp.profiles.recent_trades(WALLET, limit=3, date_from=1700000000))  # NEW param
test("profiles.historical_pnl", lambda: fp.profiles.historical_pnl(WALLET, time_period="1w"))
test("profiles.activity", lambda: fp.profiles.activity(WALLET, limit=3))
test("profiles.unredeemed_positions", lambda: fp.profiles.unredeemed_positions(WALLET))  # NEW

# --- LEADERBOARD ---
print("\n## Leaderboard")
test("leaderboard.get", lambda: fp.leaderboard.get(limit=3, timeframe="7d"))
test("leaderboard.search", lambda: fp.leaderboard.search(q="0x2eb5714", limit=3))
test("leaderboard.user", lambda: fp.leaderboard.user(WALLET))  # NEW
test("leaderboard.categories", lambda: fp.leaderboard.categories())  # NEW

# --- SEARCH ---
print("\n## Search")
test("search.markets", lambda: fp.search.markets(q="Bitcoin", limit=3))  # NEW
test("search.events", lambda: fp.search.events(q="Bitcoin", limit=3))

# --- WALLETS ---
print("\n## Wallets")
test("wallets.trades", lambda: fp.wallets.trades(WALLET, limit=3))
test("wallets.net_flows", lambda: fp.wallets.net_flows(WALLET, limit=3))

# --- NEWS ---
print("\n## News")
test("news.get", lambda: fp.news.get(limit=3))
test("news.get (significance)", lambda: fp.news.get(limit=3, min_significance=3))
test("news.get (market_id)", lambda: fp.news.get(market_id=MARKET_ID, limit=3))

# --- TRADING (read-only queries) ---
print("\n## Trading (read-only)")
if TRADING_TOKEN:
    test("trading.open_orders", lambda: fp.trading.open_orders())
else:
    print("  SKIP  trading.* — no FIREPLACE_TRADING_TOKEN set")

# --- SUMMARY ---
print("\n" + "=" * 70)
passes = sum(1 for v in results.values() if v == "PASS")
fails = sum(1 for v in results.values() if v != "PASS")
print(f"RESULTS: {passes} passed, {fails} failed out of {len(results)} tests")
if fails:
    print("\nFailed tests:")
    for name, result in results.items():
        if result != "PASS":
            print(f"  - {name}: {result}")
print("=" * 70)

fp.close()
