"""
Test Python code snippets from remaining docs files.

Files tested:
- docs/authentication.mdx
- docs/configuration.mdx
- docs/dashboard.mdx
- docs/introduction.mdx
- docs/quickstart.mdx
- docs/testing.mdx
- docs/api-reference/engine.mdx
- docs/api-reference/types.mdx
"""

import sys
import traceback

RESULTS = []


def record(name, passed, error=None):
    status = "PASS" if passed else "FAIL"
    RESULTS.append((name, status, error))
    if error:
        print(f"  {status}: {name} -- {error}")
    else:
        print(f"  {status}: {name}")


# ============================================================
# docs/authentication.mdx
# ============================================================
print("\n=== docs/authentication.mdx ===")

# Snippet 1: hz.run with api_key param (lines 59-66)
# Just verify the kwarg is accepted syntactically; we can't actually run hz.run
try:
    import horizon as hz
    # Verify hz.run accepts api_key kwarg by checking it exists
    import inspect
    sig = inspect.signature(hz.run)
    assert "api_key" in sig.parameters, "hz.run missing api_key parameter"
    record("authentication.mdx: hz.run(api_key=...) param exists", True)
except Exception as e:
    record("authentication.mdx: hz.run(api_key=...) param exists", False, str(e))

# Snippet 2: Engine(api_key=...) (lines 71-73)
try:
    from horizon import Engine, RiskConfig
    # Just check Engine accepts api_key kwarg
    import inspect
    sig = inspect.signature(Engine)
    assert "api_key" in sig.parameters, "Engine missing api_key parameter"
    record("authentication.mdx: Engine(api_key=...) param exists", True)
except Exception as e:
    record("authentication.mdx: Engine(api_key=...) param exists", False, str(e))


# ============================================================
# docs/configuration.mdx
# ============================================================
print("\n=== docs/configuration.mdx ===")

# Snippet: hz.Polymarket() constructor exists
try:
    from horizon import Polymarket
    record("configuration.mdx: hz.Polymarket import", True)
except Exception as e:
    record("configuration.mdx: hz.Polymarket import", False, str(e))

# Snippet: hz.Kalshi() constructor exists
try:
    from horizon import Kalshi
    record("configuration.mdx: hz.Kalshi import", True)
except Exception as e:
    record("configuration.mdx: hz.Kalshi import", False, str(e))

# Snippet: Polymarket with explicit constructor args
try:
    from horizon import Polymarket
    sig = inspect.signature(Polymarket)
    params = list(sig.parameters.keys())
    # Check private_key and api_key are in params
    assert "private_key" in params or any("key" in p for p in params), \
        f"Polymarket constructor params: {params}"
    record("configuration.mdx: Polymarket(private_key=..., api_key=...) signature", True)
except Exception as e:
    record("configuration.mdx: Polymarket(private_key=..., api_key=...) signature", False, str(e))


# ============================================================
# docs/dashboard.mdx
# ============================================================
print("\n=== docs/dashboard.mdx ===")

# Snippet: hz.run(dashboard=True, ...)
try:
    import inspect
    sig = inspect.signature(hz.run)
    assert "dashboard" in sig.parameters, "hz.run missing dashboard parameter"
    record("dashboard.mdx: hz.run(dashboard=True) param exists", True)
except Exception as e:
    record("dashboard.mdx: hz.run(dashboard=True) param exists", False, str(e))


# ============================================================
# docs/introduction.mdx
# ============================================================
print("\n=== docs/introduction.mdx ===")

# Snippet 1: hz.run basic example (lines 47-62)
try:
    import horizon as hz

    def fair_value_intro(ctx: hz.Context) -> float:
        return ctx.feeds["btc"].price * 0.01

    def quoter_intro(ctx: hz.Context, fair: float) -> list[hz.Quote]:
        return hz.quotes(fair, spread=0.04, size=5)

    # Verify the pipeline functions are callable and hz.quotes works
    from horizon.context import Context, FeedData
    ctx = Context(feeds={"btc": FeedData(price=50000.0)})
    fv = fair_value_intro(ctx)
    assert isinstance(fv, float), f"Expected float, got {type(fv)}"
    qs = quoter_intro(ctx, fv)
    assert len(qs) == 1, f"Expected 1 quote, got {len(qs)}"
    assert isinstance(qs[0], hz.Quote), f"Expected Quote, got {type(qs[0])}"
    record("introduction.mdx: hz.run basic example pipeline functions", True)
except Exception as e:
    record("introduction.mdx: hz.run basic example pipeline functions", False, str(e))

# Snippet 1b: hz.BinanceWS("btcusdt") and hz.Risk
try:
    feed = hz.BinanceWS("btcusdt")
    risk = hz.Risk(max_position=100, max_drawdown_pct=5)
    record("introduction.mdx: BinanceWS + Risk construction", True)
except Exception as e:
    record("introduction.mdx: BinanceWS + Risk construction", False, str(e))

# Snippet 2: hz.backtest (lines 69-77)
try:
    # We can't actually run backtest end-to-end without a real pipeline,
    # but check the function exists and accepts the right params
    import inspect
    sig = inspect.signature(hz.backtest)
    params = list(sig.parameters.keys())
    for p in ["markets", "data", "pipeline", "risk"]:
        assert p in params, f"hz.backtest missing param '{p}', has: {params}"
    record("introduction.mdx: hz.backtest signature", True)
except Exception as e:
    record("introduction.mdx: hz.backtest signature", False, str(e))

# Snippet 3: engine.submit_bracket (lines 84-91)
try:
    from horizon import OrderRequest, Side, OrderSide
    # Check submit_bracket method exists on Engine
    assert hasattr(Engine, "submit_bracket"), "Engine missing submit_bracket method"
    record("introduction.mdx: engine.submit_bracket exists", True)
except Exception as e:
    record("introduction.mdx: engine.submit_bracket exists", False, str(e))


# ============================================================
# docs/quickstart.mdx
# ============================================================
print("\n=== docs/quickstart.mdx ===")

# Snippet: Simple strategy (lines 38-56)
try:
    import horizon as hz

    def fair_value_qs(ctx: hz.Context) -> float:
        """Simple fair value: just return 0.5 (coin flip)."""
        return 0.50

    def quoter_qs(ctx: hz.Context, fair: float) -> list[hz.Quote]:
        """Quote around the fair value with a fixed spread."""
        return hz.quotes(fair, spread=0.06, size=5)

    # Verify pipeline works
    from horizon.context import Context
    ctx = Context()
    fv = fair_value_qs(ctx)
    assert fv == 0.50
    qs = quoter_qs(ctx, fv)
    assert len(qs) == 1
    q = qs[0]
    assert abs(q.bid - 0.47) < 1e-9, f"bid={q.bid}"
    assert abs(q.ask - 0.53) < 1e-9, f"ask={q.ask}"
    assert q.size == 5.0

    # Verify hz.run accepts the params shown
    sig = inspect.signature(hz.run)
    for p in ["name", "markets", "pipeline", "risk", "interval", "mode"]:
        assert p in sig.parameters, f"hz.run missing param '{p}'"
    record("quickstart.mdx: simple strategy pipeline + hz.run params", True)
except Exception as e:
    record("quickstart.mdx: simple strategy pipeline + hz.run params", False, str(e))


# ============================================================
# docs/testing.mdx
# ============================================================
print("\n=== docs/testing.mdx ===")

# Snippet 1: test_my_strategy_logic (lines 64-87)
try:
    from horizon import Engine, RiskConfig, OrderRequest, Side, OrderSide, Quote, Fill
    config = RiskConfig(max_position_per_market=1000)
    engine = Engine(risk_config=config)

    order_id = engine.submit_order(OrderRequest(
        market_id="test",
        side=Side.Yes,
        order_side=OrderSide.Buy,
        size=10.0,
        price=0.55,
    ))

    fills = engine.tick("test", 0.55)
    assert fills == 1, f"Expected 1 fill, got {fills}"

    positions = engine.positions()
    assert len(positions) == 1, f"Expected 1 position, got {len(positions)}"
    assert positions[0].size == 10.0, f"Expected size 10.0, got {positions[0].size}"
    record("testing.mdx: test_my_strategy_logic", True)
except Exception as e:
    record("testing.mdx: test_my_strategy_logic", False, str(e))

# Snippet 2: test_position_tracking (lines 94-111)
try:
    engine2 = Engine()
    engine2.process_fill(Fill(
        fill_id="f1",
        order_id="o1",
        market_id="test",
        side=Side.Yes,
        order_side=OrderSide.Buy,
        price=0.50,
        size=10.0,
    ))

    positions = engine2.positions()
    assert len(positions) == 1, f"Expected 1 position, got {len(positions)}"
    assert positions[0].avg_entry_price == 0.50, \
        f"Expected avg_entry_price 0.50, got {positions[0].avg_entry_price}"
    record("testing.mdx: test_position_tracking", True)
except Exception as e:
    record("testing.mdx: test_position_tracking", False, str(e))

# Snippet 3: test_position_limit (lines 116-137)
try:
    config3 = RiskConfig(max_position_per_market=10.0)
    engine3 = Engine(risk_config=config3)

    engine3.process_fill(Fill(
        fill_id="f1", order_id="o1", market_id="test",
        side=Side.Yes, order_side=OrderSide.Buy,
        price=0.50, size=10.0,
    ))

    # This should be rejected by the position limit
    import pytest
    try:
        engine3.submit_order(OrderRequest(
            market_id="test",
            side=Side.Yes,
            order_side=OrderSide.Buy,
            size=5.0,
            price=0.55,
        ))
        # If no exception, that's a fail for the docs assertion
        record("testing.mdx: test_position_limit (expected exception)", False,
               "No exception raised for position limit violation")
    except Exception:
        record("testing.mdx: test_position_limit (expected exception)", True)
except Exception as e:
    record("testing.mdx: test_position_limit", False, str(e))

# Snippet 4: test_fair_value with Context (lines 144-161)
try:
    from horizon.context import Context, FeedData, InventorySnapshot

    ctx = Context(
        feeds={"btc": FeedData(price=100_000, bid=99_990, ask=100_010)},
    )
    assert ctx.feeds["btc"].price == 100_000
    assert ctx.feeds["btc"].bid == 99_990
    assert ctx.feeds["btc"].ask == 100_010

    ctx2 = Context(
        feeds={"btc": FeedData(price=100_000)},
        inventory=InventorySnapshot(positions=[]),
    )
    assert ctx2.inventory.positions == []

    record("testing.mdx: Context construction with FeedData/InventorySnapshot", True)
except Exception as e:
    record("testing.mdx: Context construction with FeedData/InventorySnapshot", False, str(e))

# Snippet 5: test_crash_recovery (lines 166-191)
try:
    import tempfile, os

    with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as f:
        db_path = f.name

    try:
        # First run: build some state
        engine_cr = Engine(db_path=db_path)
        engine_cr.process_fill(Fill(
            fill_id="f1", order_id="o1", market_id="test",
            side=Side.Yes, order_side=OrderSide.Buy,
            price=0.50, size=10.0,
        ))
        engine_cr.snapshot_positions()
        del engine_cr

        # Second run: recover state
        engine_cr2 = Engine(db_path=db_path)
        recovered = engine_cr2.recover_state()
        assert recovered == 1, f"Expected 1 recovered, got {recovered}"
        positions = engine_cr2.positions()
        assert len(positions) == 1, f"Expected 1 position, got {len(positions)}"
        record("testing.mdx: test_crash_recovery", True)
    finally:
        os.unlink(db_path)
except Exception as e:
    record("testing.mdx: test_crash_recovery", False, str(e))


# ============================================================
# docs/api-reference/engine.mdx
# ============================================================
print("\n=== docs/api-reference/engine.mdx ===")

# Snippet: Engine construction variants
try:
    e1 = Engine()
    e2 = Engine(risk_config=RiskConfig(max_position_per_market=200))
    e3 = Engine(paper_fee_rate=0.001, paper_partial_fill_ratio=0.5)
    record("engine.mdx: Engine() construction variants", True)
except Exception as e:
    record("engine.mdx: Engine() construction variants", False, str(e))

# Snippet: Engine with persistence
try:
    import tempfile
    with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as f:
        db_path = f.name
    try:
        e_db = Engine(db_path=db_path)
        assert e_db.has_persistence()
        del e_db
    finally:
        os.unlink(db_path)

    e_nodb = Engine(db_path=None)
    record("engine.mdx: Engine with/without persistence", True)
except Exception as e:
    record("engine.mdx: Engine with/without persistence", False, str(e))

# Snippet: Full Engine signature params
try:
    sig = inspect.signature(Engine)
    expected_params = [
        "risk_config", "paper_fee_rate", "exchange_type",
        "exchange_key", "exchange_secret", "exchange_passphrase",
        "clob_url", "api_url", "email", "password", "private_key",
        "paper_partial_fill_ratio", "db_path", "api_key",
        "paper_maker_fee_rate", "paper_taker_fee_rate",
    ]
    missing = [p for p in expected_params if p not in sig.parameters]
    assert not missing, f"Engine missing params: {missing}"
    record("engine.mdx: Engine full signature", True)
except Exception as e:
    record("engine.mdx: Engine full signature", False, str(e))

# Snippet: Maker/taker fees
try:
    e_flat = Engine(paper_fee_rate=0.001)
    e_split = Engine(paper_maker_fee_rate=0.0002, paper_taker_fee_rate=0.002)
    e_mixed = Engine(paper_fee_rate=0.001, paper_taker_fee_rate=0.003)
    record("engine.mdx: maker/taker fee construction", True)
except Exception as e:
    record("engine.mdx: maker/taker fee construction", False, str(e))

# Snippet: add_exchange method exists
try:
    assert hasattr(Engine, "add_exchange"), "Engine missing add_exchange"
    record("engine.mdx: add_exchange method exists", True)
except Exception as e:
    record("engine.mdx: add_exchange method exists", False, str(e))

# Snippet: exchange_names, exchange_count, exchange_name
try:
    e_multi = Engine()
    names = e_multi.exchange_names()
    assert isinstance(names, list)
    count = e_multi.exchange_count()
    assert isinstance(count, int)
    name = e_multi.exchange_name()
    assert isinstance(name, str)
    record("engine.mdx: exchange_names/count/name", True)
except Exception as e:
    record("engine.mdx: exchange_names/count/name", False, str(e))

# Snippet: set_netting_pair / netting_pairs
try:
    e_net = Engine()
    e_net.set_netting_pair("market_a", "market_b")
    pairs = e_net.netting_pairs()
    assert len(pairs) == 1
    assert pairs[0] == ("market_a", "market_b"), f"Got {pairs[0]}"
    record("engine.mdx: set_netting_pair / netting_pairs", True)
except Exception as e:
    record("engine.mdx: set_netting_pair / netting_pairs", False, str(e))

# Snippet: submit_order
try:
    e_so = Engine(risk_config=RiskConfig(max_position_per_market=1000))
    oid = e_so.submit_order(OrderRequest(
        market_id="test", side=Side.Yes, order_side=OrderSide.Buy,
        size=10.0, price=0.55,
    ))
    assert isinstance(oid, str)
    record("engine.mdx: submit_order", True)
except Exception as e:
    record("engine.mdx: submit_order", False, str(e))

# Snippet: submit_quotes
try:
    e_sq = Engine(risk_config=RiskConfig(max_position_per_market=1000))
    ids = e_sq.submit_quotes(
        "test-market",
        [hz.Quote(bid=0.45, ask=0.55, size=10.0)],
        Side.Yes,
    )
    assert isinstance(ids, list)
    record("engine.mdx: submit_quotes", True)
except Exception as e:
    record("engine.mdx: submit_quotes", False, str(e))

# Snippet: amend_order
try:
    e_am = Engine(risk_config=RiskConfig(max_position_per_market=1000))
    oid_am = e_am.submit_order(OrderRequest(
        market_id="test", side=Side.Yes, order_side=OrderSide.Buy,
        size=10.0, price=0.55,
    ))
    new_id = e_am.amend_order(oid_am, new_price=0.60, new_size=15.0)
    assert isinstance(new_id, str)
    record("engine.mdx: amend_order", True)
except Exception as e:
    record("engine.mdx: amend_order", False, str(e))

# Snippet: add_stop_loss / add_take_profit
try:
    e_sl = Engine(risk_config=RiskConfig(max_position_per_market=1000))
    sl_id = e_sl.add_stop_loss(
        "test-market", Side.Yes, OrderSide.Sell, 10.0, 0.45,
    )
    assert isinstance(sl_id, str)

    tp_id = e_sl.add_take_profit(
        "test-market", Side.Yes, OrderSide.Sell, 10.0, 0.70,
    )
    assert isinstance(tp_id, str)
    record("engine.mdx: add_stop_loss / add_take_profit", True)
except Exception as e:
    record("engine.mdx: add_stop_loss / add_take_profit", False, str(e))

# Snippet: submit_bracket
try:
    e_br = Engine(risk_config=RiskConfig(max_position_per_market=1000))
    entry_id, sl_id_br, tp_id_br = e_br.submit_bracket(
        request=OrderRequest(market_id="test", side=Side.Yes,
                             order_side=OrderSide.Buy, size=10, price=0.55),
        stop_trigger=0.45,
        take_profit_trigger=0.70,
    )
    assert isinstance(entry_id, str)
    assert isinstance(sl_id_br, str)
    assert isinstance(tp_id_br, str)
    record("engine.mdx: submit_bracket", True)
except Exception as e:
    record("engine.mdx: submit_bracket", False, str(e))

# Snippet: check_contingent_triggers
try:
    e_ct = Engine(risk_config=RiskConfig(max_position_per_market=1000))
    triggered = e_ct.check_contingent_triggers("test-market", 0.50)
    assert isinstance(triggered, int)
    record("engine.mdx: check_contingent_triggers", True)
except Exception as e:
    record("engine.mdx: check_contingent_triggers", False, str(e))

# Snippet: pending_contingent_orders
try:
    e_pco = Engine()
    pending = e_pco.pending_contingent_orders()
    assert isinstance(pending, list)
    record("engine.mdx: pending_contingent_orders", True)
except Exception as e:
    record("engine.mdx: pending_contingent_orders", False, str(e))

# Snippet: submit_order_smart exists
try:
    assert hasattr(Engine, "submit_order_smart"), "Engine missing submit_order_smart"
    record("engine.mdx: submit_order_smart exists", True)
except Exception as e:
    record("engine.mdx: submit_order_smart exists", False, str(e))

# Snippet: cancel / cancel_all / cancel_market
try:
    e_can = Engine(risk_config=RiskConfig(max_position_per_market=1000))
    oid_can = e_can.submit_order(OrderRequest(
        market_id="test", side=Side.Yes, order_side=OrderSide.Buy,
        size=10.0, price=0.55,
    ))
    e_can.cancel(oid_can)

    count_all = e_can.cancel_all()
    assert isinstance(count_all, int)

    count_mkt = e_can.cancel_market("test")
    assert isinstance(count_mkt, int)
    record("engine.mdx: cancel / cancel_all / cancel_market", True)
except Exception as e:
    record("engine.mdx: cancel / cancel_all / cancel_market", False, str(e))

# Snippet: tick / poll_fills / process_fill
try:
    e_tf = Engine(risk_config=RiskConfig(max_position_per_market=1000))
    oid_tf = e_tf.submit_order(OrderRequest(
        market_id="test", side=Side.Yes, order_side=OrderSide.Buy,
        size=10.0, price=0.55,
    ))
    fc = e_tf.tick("test", 0.55)
    assert isinstance(fc, int)

    pf = e_tf.poll_fills()
    assert isinstance(pf, int)

    e_tf.process_fill(Fill(
        fill_id="f99", order_id="o99", market_id="test",
        side=Side.Yes, order_side=OrderSide.Buy,
        price=0.50, size=1.0,
    ))
    record("engine.mdx: tick / poll_fills / process_fill", True)
except Exception as e:
    record("engine.mdx: tick / poll_fills / process_fill", False, str(e))

# Snippet: update_mark_price
try:
    e_mp = Engine()
    e_mp.process_fill(Fill(
        fill_id="f1", order_id="o1", market_id="test",
        side=Side.Yes, order_side=OrderSide.Buy,
        price=0.50, size=10.0,
    ))
    e_mp.update_mark_price("test", Side.Yes, 0.60)
    record("engine.mdx: update_mark_price", True)
except Exception as e:
    record("engine.mdx: update_mark_price", False, str(e))

# Snippet: queries (open_orders, positions, recent_fills, status)
try:
    e_q = Engine()
    orders = e_q.open_orders()
    assert isinstance(orders, list)
    positions = e_q.positions()
    assert isinstance(positions, list)
    fills = e_q.recent_fills()
    assert isinstance(fills, list)
    status = e_q.status()
    assert status is not None
    record("engine.mdx: open_orders / positions / recent_fills / status", True)
except Exception as e:
    record("engine.mdx: open_orders / positions / recent_fills / status", False, str(e))

# Snippet: open_orders_for_market
try:
    e_ofm = Engine()
    orders_mkt = e_ofm.open_orders_for_market("test")
    assert isinstance(orders_mkt, list)
    record("engine.mdx: open_orders_for_market", True)
except Exception as e:
    record("engine.mdx: open_orders_for_market", False, str(e))

# Snippet: risk controls
try:
    e_rc = Engine()
    e_rc.activate_kill_switch("manual halt")
    e_rc.deactivate_kill_switch()
    e_rc.update_daily_pnl(100.0)
    e_rc.set_daily_baseline(0.0)
    record("engine.mdx: risk controls (kill_switch, daily_pnl, baseline)", True)
except Exception as e:
    record("engine.mdx: risk controls (kill_switch, daily_pnl, baseline)", False, str(e))

# Snippet: feed management start_feed
try:
    import json
    e_fm = Engine()
    e_fm.start_feed("btc", "binance_ws", symbol="btcusdt")
    e_fm.start_feed("custom", "rest", url="https://example.com/price", interval=5.0)
    e_fm.start_feed("pi", "predictit", config_json=json.dumps({"market_id": 7456}))
    e_fm.start_feed("mf", "manifold", config_json=json.dumps({"slug": "test-market"}))
    e_fm.start_feed("nba", "espn", config_json=json.dumps({"sport": "basketball", "league": "nba"}))
    e_fm.start_feed("wx", "nws", config_json=json.dumps({"mode": "alerts", "state": "FL"}))
    e_fm.start_feed("cg", "rest_json_path", config_json=json.dumps({
        "url": "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd",
        "price_path": "bitcoin.usd",
    }))
    record("engine.mdx: start_feed (various types)", True)
except Exception as e:
    record("engine.mdx: start_feed (various types)", False, str(e))

# Snippet: feed query methods
try:
    e_fq = Engine()
    snap = e_fq.feed_snapshot("nonexistent")
    # snap is None if feed doesn't exist
    all_snaps = e_fq.all_feed_snapshots()
    assert isinstance(all_snaps, dict)
    record("engine.mdx: feed_snapshot / all_feed_snapshots", True)
except Exception as e:
    record("engine.mdx: feed_snapshot / all_feed_snapshots", False, str(e))

# Snippet: feed_age
try:
    e_fa = Engine()
    age = e_fa.feed_age("nonexistent")
    # Returns None or a float
    record("engine.mdx: feed_age", True)
except Exception as e:
    record("engine.mdx: feed_age", False, str(e))

# Snippet: stop_feed / restart_feed / is_feed_running
try:
    e_fc = Engine()
    e_fc.start_feed("test_btc", "binance_ws", symbol="btcusdt")
    running = e_fc.is_feed_running("test_btc")
    assert isinstance(running, bool)
    e_fc.stop_feed("test_btc")
    e_fc.stop_feeds()
    record("engine.mdx: stop_feed / is_feed_running / stop_feeds", True)
except Exception as e:
    record("engine.mdx: stop_feed / is_feed_running / stop_feeds", False, str(e))

# Snippet: persistence methods
try:
    import tempfile
    with tempfile.NamedTemporaryFile(suffix=".db", delete=False) as f:
        db_path = f.name
    try:
        e_ps = Engine(db_path=db_path)
        assert e_ps.has_persistence()
        sc = e_ps.snapshot_positions()
        assert isinstance(sc, int)
        rc = e_ps.recover_state()
        assert isinstance(rc, int)
        e_ps.start_run("strategy")
        rid = e_ps.db_run_id()
        # rid may be str or None
        ooids = e_ps.db_open_order_ids()
        assert isinstance(ooids, list)
        e_ps.end_run()
        del e_ps
    finally:
        os.unlink(db_path)
    record("engine.mdx: persistence methods", True)
except Exception as e:
    record("engine.mdx: persistence methods", False, str(e))

# Snippet: register_event / event methods
try:
    e_ev = Engine()
    e_ev.register_event("election-2024", ["trump-win", "biden-win", "desantis-win"])
    exp = e_ev.event_exposure("election-2024")
    assert isinstance(exp, float)
    epos = e_ev.event_positions("election-2024")
    assert isinstance(epos, list)
    mid = e_ev.market_event_id("trump-win")
    assert mid == "election-2024", f"Got {mid}"
    evts = e_ev.registered_events()
    assert isinstance(evts, dict)
    assert "election-2024" in evts
    record("engine.mdx: register_event / event methods", True)
except Exception as e:
    record("engine.mdx: register_event / event methods", False, str(e))

# Snippet: event_parity_check
try:
    e_pc = Engine()
    e_pc.register_event("test-event", ["m1", "m2"])
    result = e_pc.event_parity_check("test-event", threshold=0.02)
    # Returns ParityResult or None
    record("engine.mdx: event_parity_check", True)
except Exception as e:
    record("engine.mdx: event_parity_check", False, str(e))

# Snippet: execute_arbitrage exists
try:
    assert hasattr(Engine, "execute_arbitrage"), "Engine missing execute_arbitrage"
    record("engine.mdx: execute_arbitrage exists", True)
except Exception as e:
    record("engine.mdx: execute_arbitrage exists", False, str(e))

# Snippet: evict_stale_orders
try:
    e_eso = Engine()
    e_eso.evict_stale_orders(max_age_secs=300.0)
    record("engine.mdx: evict_stale_orders", True)
except Exception as e:
    record("engine.mdx: evict_stale_orders", False, str(e))


# ============================================================
# docs/api-reference/types.mdx
# ============================================================
print("\n=== docs/api-reference/types.mdx ===")

# Snippet: Enum imports
try:
    from horizon import Side, OrderSide, OrderType, TimeInForce, OrderStatus, AlertLevel, TriggerType, ContingentOrder
    assert Side.Yes is not None
    assert Side.No is not None
    assert OrderSide.Buy is not None
    assert OrderSide.Sell is not None
    assert OrderType.Limit is not None
    assert OrderType.Market is not None
    assert TimeInForce.GTC is not None
    assert TimeInForce.GTD is not None
    assert TimeInForce.FOK is not None
    assert TimeInForce.FAK is not None
    assert OrderStatus.New is not None
    assert OrderStatus.Submitted is not None
    assert OrderStatus.Accepted is not None
    assert OrderStatus.PartiallyFilled is not None
    assert OrderStatus.Filled is not None
    assert OrderStatus.Canceled is not None
    assert OrderStatus.Rejected is not None
    assert AlertLevel.Info is not None
    assert AlertLevel.Warning is not None
    assert AlertLevel.Critical is not None
    assert TriggerType.StopLoss is not None
    assert TriggerType.TakeProfit is not None
    record("types.mdx: all enum values exist", True)
except Exception as e:
    record("types.mdx: all enum values exist", False, str(e))

# Snippet: Quote construction and methods
try:
    quote = hz.Quote(bid=0.45, ask=0.55, size=10.0)
    assert quote.bid == 0.45
    assert quote.ask == 0.55
    assert quote.size == 10.0
    assert abs(quote.spread() - 0.10) < 1e-9, f"spread={quote.spread()}"
    assert abs(quote.mid() - 0.50) < 1e-9, f"mid={quote.mid()}"
    record("types.mdx: Quote construction and methods", True)
except Exception as e:
    record("types.mdx: Quote construction and methods", False, str(e))

# Snippet: quotes() helper
try:
    quotes = hz.quotes(fair=0.50, spread=0.06, size=5.0)
    assert len(quotes) == 1
    assert abs(quotes[0].bid - 0.47) < 1e-9
    assert abs(quotes[0].ask - 0.53) < 1e-9
    assert quotes[0].size == 5.0
    record("types.mdx: hz.quotes() helper", True)
except Exception as e:
    record("types.mdx: hz.quotes() helper", False, str(e))

# Snippet: Market construction
try:
    market = hz.Market(
        id="will-btc-hit-100k",
        name="Will BTC hit $100k?",
        slug="will-btc-hit-100k",
        exchange="polymarket",
        expiry="2025-12-31",
        active=True,
        yes_token_id="123456789",
        no_token_id="987654321",
        condition_id="0xabc",
        neg_risk=True,
        ticker="KXBTC-25FEB16",
    )
    assert market.id == "will-btc-hit-100k"
    assert market.token_id(Side.Yes) == "123456789"
    assert market.token_id(Side.No) == "987654321"
    record("types.mdx: Market construction + token_id()", True)
except Exception as e:
    record("types.mdx: Market construction + token_id()", False, str(e))

# Snippet: Outcome construction
try:
    from horizon import Outcome
    outcome = Outcome(
        name="Trump",
        market_id="trump-wins-2024",
        yes_token_id="token_yes_123",
        no_token_id="token_no_456",
        yes_price=0.55,
    )
    assert outcome.token_id(Side.Yes) == "token_yes_123"
    assert outcome.token_id(Side.No) == "token_no_456"
    record("types.mdx: Outcome construction + token_id()", True)
except Exception as e:
    record("types.mdx: Outcome construction + token_id()", False, str(e))

# Snippet: Event construction and methods
try:
    from horizon import Event, Outcome
    trump = Outcome(name="Trump", market_id="trump-win", yes_token_id="t1", yes_price=0.55)
    biden = Outcome(name="Biden", market_id="biden-win", yes_token_id="t2", yes_price=0.35)
    desantis = Outcome(name="DeSantis", market_id="desantis-win", yes_token_id="t3", yes_price=0.10)

    event = Event(
        id="election-2024",
        name="Who wins the 2024 election?",
        outcomes=[trump, biden, desantis],
        neg_risk=True,
        exchange="polymarket",
        condition_id="0xabc",
    )

    assert event.outcome_count() == 3
    names = event.outcome_names()
    assert "Trump" in names
    assert "Biden" in names
    assert "DeSantis" in names
    found = event.outcome_by_name("Trump")
    assert found is not None
    markets = event.to_markets()
    assert isinstance(markets, list)
    record("types.mdx: Event construction + methods", True)
except Exception as e:
    record("types.mdx: Event construction + methods", False, str(e))

# Snippet: OrderRequest construction
try:
    req = hz.OrderRequest(
        market_id="will-btc-hit-100k",
        side=Side.Yes,
        order_side=OrderSide.Buy,
        size=10.0,
        price=0.55,
        order_type=OrderType.Limit,
        time_in_force=TimeInForce.GTC,
        post_only=True,
        token_id="123456789",
        neg_risk=False,
    )
    assert req.market_id == "will-btc-hit-100k"
    assert req.side == Side.Yes
    assert req.order_side == OrderSide.Buy
    assert req.size == 10.0
    assert req.price == 0.55
    record("types.mdx: OrderRequest construction", True)
except Exception as e:
    record("types.mdx: OrderRequest construction", False, str(e))

# Snippet: Order fields (via engine)
try:
    e_ord = Engine(risk_config=RiskConfig(max_position_per_market=1000))
    oid_ord = e_ord.submit_order(OrderRequest(
        market_id="test", side=Side.Yes, order_side=OrderSide.Buy,
        size=10.0, price=0.55,
    ))
    orders = e_ord.open_orders()
    assert len(orders) >= 1
    o = orders[0]
    # Check documented fields exist
    _ = o.id
    _ = o.market_id
    _ = o.side
    _ = o.order_side
    _ = o.price
    _ = o.size
    _ = o.filled_size
    _ = o.remaining_size
    _ = o.status
    _ = o.created_at
    _ = o.exchange
    _ = o.amendment_count
    _ = o.is_open()
    record("types.mdx: Order fields and is_open()", True)
except Exception as e:
    record("types.mdx: Order fields and is_open()", False, str(e))

# Snippet: Position fields (via fill)
try:
    e_pos = Engine()
    e_pos.process_fill(Fill(
        fill_id="f1", order_id="o1", market_id="will-btc-hit-100k",
        side=Side.Yes, order_side=OrderSide.Buy,
        price=0.55, size=10.0,
    ))
    pos = e_pos.positions()[0]
    _ = pos.market_id
    _ = pos.side
    _ = pos.size
    _ = pos.avg_entry_price
    _ = pos.realized_pnl
    _ = pos.unrealized_pnl
    _ = pos.exchange
    _ = pos.total_pnl()
    _ = pos.notional()
    record("types.mdx: Position fields + total_pnl() + notional()", True)
except Exception as e:
    record("types.mdx: Position fields + total_pnl() + notional()", False, str(e))

# Snippet: Fill construction
try:
    fill = hz.Fill(
        fill_id="fill_001",
        order_id="order_001",
        market_id="will-btc-hit-100k",
        side=Side.Yes,
        order_side=OrderSide.Buy,
        price=0.55,
        size=10.0,
        fee=0.01,
        timestamp=1700000000.0,
        token_id="123456789",
        exchange="polymarket",
        is_maker=False,
    )
    assert fill.fill_id == "fill_001"
    assert fill.is_maker == False
    record("types.mdx: Fill construction with is_maker", True)
except Exception as e:
    record("types.mdx: Fill construction with is_maker", False, str(e))

# Snippet: SimPosition
try:
    pos_sim = hz.SimPosition(
        market_id="election-winner",
        side="yes",
        size=100.0,
        entry_price=0.50,
        current_price=0.60,
    )
    assert pos_sim.market_id == "election-winner"
    assert pos_sim.side == "yes"
    assert pos_sim.size == 100.0
    assert pos_sim.entry_price == 0.50
    assert pos_sim.current_price == 0.60
    record("types.mdx: SimPosition construction", True)
except Exception as e:
    record("types.mdx: SimPosition construction", False, str(e))

# Snippet: SimulationResult (via monte_carlo)
try:
    positions_sim = [
        hz.SimPosition(market_id="m1", side="yes", size=100.0,
                       entry_price=0.50, current_price=0.60),
    ]
    result_sim = hz.monte_carlo(positions_sim, 10000, None, 42)
    _ = result_sim.mean_pnl
    _ = result_sim.median_pnl
    _ = result_sim.std_dev
    _ = result_sim.var_95
    _ = result_sim.var_99
    _ = result_sim.cvar_95
    _ = result_sim.max_loss
    _ = result_sim.max_gain
    _ = result_sim.win_probability
    _ = result_sim.scenario_pnl
    _ = result_sim.percentiles
    record("types.mdx: SimulationResult fields via monte_carlo()", True)
except Exception as e:
    record("types.mdx: SimulationResult fields via monte_carlo()", False, str(e))

# Snippet: EngineStatus fields
try:
    e_es = Engine()
    status = e_es.status()
    _ = status.running
    _ = status.kill_switch_active
    _ = status.kill_switch_reason
    _ = status.open_orders
    _ = status.active_positions
    _ = status.total_realized_pnl
    _ = status.total_unrealized_pnl
    _ = status.daily_pnl
    _ = status.uptime_secs
    _ = status.total_pnl()
    record("types.mdx: EngineStatus fields + total_pnl()", True)
except Exception as e:
    record("types.mdx: EngineStatus fields + total_pnl()", False, str(e))

# Snippet: FeedSnapshot fields (from engine)
try:
    # Can't easily test without a running feed; just verify the type imports
    from horizon import FeedSnapshot
    record("types.mdx: FeedSnapshot import", True)
except Exception as e:
    record("types.mdx: FeedSnapshot import", False, str(e))

# Snippet: RiskConfig construction
try:
    config = RiskConfig(
        max_position_per_market=100.0,
        max_portfolio_notional=1000.0,
        max_daily_drawdown_pct=5.0,
        max_order_size=50.0,
        rate_limit_sustained=50,
        rate_limit_burst=300,
        dedup_window_ms=1000,
        max_position_per_event=200.0,
    )
    record("types.mdx: RiskConfig construction (with max_position_per_event)", True)
except Exception as e:
    record("types.mdx: RiskConfig construction (with max_position_per_event)", False, str(e))

# Snippet: EventArbitrageOpportunity fields (just check import)
try:
    from horizon import EventArbitrageOpportunity
    record("types.mdx: EventArbitrageOpportunity import", True)
except Exception as e:
    record("types.mdx: EventArbitrageOpportunity import", False, str(e))

# Snippet: ContingentOrder fields (via engine)
try:
    e_co = Engine(risk_config=RiskConfig(max_position_per_market=1000))
    sl_id_co = e_co.add_stop_loss("test", Side.Yes, OrderSide.Sell, 10.0, 0.45)
    pending = e_co.pending_contingent_orders()
    assert len(pending) >= 1
    co = pending[0]
    _ = co.id
    _ = co.trigger_type
    _ = co.market_id
    _ = co.side
    _ = co.order_side
    _ = co.size
    _ = co.trigger_price
    _ = co.trigger_pnl
    _ = co.linked_order_id
    _ = co.exchange
    _ = co.triggered
    _ = co.child_order_id
    record("types.mdx: ContingentOrder fields", True)
except Exception as e:
    record("types.mdx: ContingentOrder fields", False, str(e))


# ============================================================
# SUMMARY
# ============================================================
print("\n" + "=" * 60)
print("SUMMARY")
print("=" * 60)

pass_count = sum(1 for _, s, _ in RESULTS if s == "PASS")
fail_count = sum(1 for _, s, _ in RESULTS if s == "FAIL")

for name, status, error in RESULTS:
    if status == "FAIL":
        print(f"  FAIL: {name}")
        if error:
            print(f"        {error}")

print(f"\nTotal: {len(RESULTS)} snippets | PASS: {pass_count} | FAIL: {fail_count}")

if fail_count > 0:
    sys.exit(1)
