"""Diagnostic: run the timing strategy briefly and log each step."""
import signal
import time
import logging
import horizon as hz
from horizon.context import FeedData

logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("diag")

# Step 1: Create a paper engine and start the feed
engine = hz.Engine()

log.info("Starting PolymarketBook feed for 'will-jesus-christ-return-before-2027'...")
market_slug = "will-jesus-christ-return-before-2027"

# Resolve token first to see what we get
from horizon.strategy import _resolve_polymarket_token
token_id = _resolve_polymarket_token(market_slug)
log.info("Resolved token ID: %s", token_id[:30] if len(token_id) > 30 else token_id)

# Start feed with resolved token
engine.start_feed("book", "polymarket_book", symbol=token_id)

# Wait for feed data
log.info("Waiting for feed data...")
for i in range(10):
    time.sleep(1)
    snap = engine.feed_snapshot("book")
    if snap:
        log.info(
            "  Feed snapshot: price=%.4f bid=%.4f ask=%.4f ts=%.1f source=%s",
            snap.price, snap.bid, snap.ask, snap.timestamp, snap.source,
        )
        if snap.price > 0 or snap.bid > 0:
            log.info("  Feed is LIVE")
            break
    else:
        log.info("  No snapshot yet (attempt %d/10)", i + 1)

# Check staleness
snap = engine.feed_snapshot("book")
if snap:
    fd = FeedData(
        price=snap.price, timestamp=snap.timestamp,
        bid=snap.bid, ask=snap.ask, volume_24h=snap.volume_24h,
        source=snap.source,
    )
    log.info("FeedData: price=%.4f bid=%.4f ask=%.4f", fd.price, fd.bid, fd.ask)
    log.info("is_stale(5)=%s  is_stale(30)=%s  timestamp=%.1f  age=%.1fs",
             fd.is_stale(5), fd.is_stale(30), fd.timestamp,
             time.time() - fd.timestamp if fd.timestamp > 0 else -1)
else:
    log.error("NO FEED DATA after 10 seconds - feed never connected!")

# Step 2: Simulate the pipeline manually
log.info("\n--- Simulating pipeline manually ---")
from horizon._horizon import Market, Side
from horizon.context import Context, InventorySnapshot

market = Market(id=market_slug, name=market_slug, slug=market_slug)
feed_data = {}
if snap:
    feed_data["book"] = FeedData(
        price=snap.price, timestamp=snap.timestamp,
        bid=snap.bid, ask=snap.ask,
    )
else:
    feed_data["book"] = FeedData()

ctx = Context(
    feeds=feed_data,
    inventory=InventorySnapshot(positions=engine.positions_for_market(market_slug)),
    market=market,
    status=engine.status(),
    params={"position_size": 10},
)

# Run timing_logic
from datetime import datetime
_last_buy_time = {}
_holding_position = {}

def timing_logic(ctx):
    slug = ctx.market.slug
    current_time = datetime.now().timestamp()
    if slug not in _holding_position:
        _holding_position[slug] = False
        _last_buy_time[slug] = 0.0
    net_pos = ctx.inventory.net_for_market(ctx.market.id)
    if net_pos > 0 and _holding_position[slug]:
        time_held = current_time - _last_buy_time[slug]
        if time_held >= 10.0:
            _holding_position[slug] = False
            return {"action": "sell", "size": float(net_pos)}
    if net_pos <= 0:
        _holding_position[slug] = True
        _last_buy_time[slug] = current_time
        return {"action": "buy"}
    return None

def execute_trade(ctx, signal_val):
    if signal_val is None:
        log.info("  execute_trade: signal is None, returning []")
        return []
    feed = ctx.feeds.get("book")
    log.info("  execute_trade: feed=%s", feed)
    if not feed:
        log.info("  execute_trade: no feed, returning []")
        return []
    log.info("  execute_trade: feed.is_stale(5)=%s", feed.is_stale(5))
    if feed.is_stale(5):
        log.info("  execute_trade: feed is STALE (ts=%.1f, age=%.1fs), returning []",
                 feed.timestamp, time.time() - feed.timestamp if feed.timestamp > 0 else -1)
        return []
    size = ctx.params.get("position_size", 10)
    if signal_val["action"] == "buy":
        ask_price = feed.ask if feed.ask > 0 else feed.price
        log.info("  execute_trade: BUY action -> Quote(bid=0, ask=%.4f, size=%s)", ask_price, size)
        quote = hz.Quote(bid=0, ask=ask_price, size=size)
        log.info("  Quote created: bid=%.4f ask=%.4f size=%.1f", quote.bid, quote.ask, quote.size)
        return [quote]
    elif signal_val["action"] == "sell":
        bid_price = feed.bid if feed.bid > 0 else feed.price
        sell_size = signal_val["size"]
        log.info("  execute_trade: SELL action -> Quote(bid=%.4f, ask=1.0, size=%s)", bid_price, sell_size)
        return [hz.Quote(bid=bid_price, ask=1.0, size=sell_size)]
    return []

# Run pipeline
signal_val = timing_logic(ctx)
log.info("timing_logic returned: %s", signal_val)

result = execute_trade(ctx, signal_val)
log.info("execute_trade returned: %s", result)

if result:
    for q in result:
        log.info("  Quote: bid=%.4f ask=%.4f size=%.1f mid=%.4f", q.bid, q.ask, q.size, q.mid())

    # Try submitting
    log.info("\n--- Attempting order submission ---")
    # First tick the paper exchange
    if snap and snap.price > 0:
        tick_price = (snap.bid + snap.ask) / 2 if snap.bid > 0 and snap.ask > 0 else snap.price
        log.info("Ticking paper exchange at %.4f", tick_price)
        engine.tick(market_slug, tick_price)

    for q in result:
        try:
            engine.submit_quotes(market_slug, [q], Side.Yes)
            log.info("  Submitted quote successfully")
        except Exception as e:
            log.error("  Submit failed: %s", e)

    st = engine.status()
    log.info("After submit: orders=%d positions=%d", st.open_orders, st.active_positions)
    for o in engine.open_orders():
        log.info("  Order: id=%s side=%s price=%.4f size=%.1f", o.id, o.order_side, o.price, o.size)
else:
    log.warning("No quotes generated - nothing to submit!")

# Step 3: The REAL issue - explain what Quote(bid=0, ask=X) does
log.info("\n--- Quote semantics analysis ---")
log.info("Quote(bid=0, ask=X) creates:")
log.info("  - A BUY order at price 0.00 (will NEVER fill)")
log.info("  - A SELL order at price X (requires existing position)")
log.info("")
log.info("To BUY YES aggressively, you should use:")
log.info("  Quote(bid=ask_price, ask=0.99, size=size)")
log.info("  This places a BUY at the ask price (fills immediately on tick)")

engine.stop_feeds()
log.info("Done.")
