#!/usr/bin/env python3
"""
Seed the markets table with resolution data from on-chain.
Run on the Pi: python3 scripts/seed_markets.py
"""
import sys
sys.path.insert(0, "backend")

from db import init_db, resolve_market, save_market, _conn
from config import TURBO_CONTRACT_ADDRESS, MONAD_RPC_URL
from web3 import Web3
import json

w3 = Web3(Web3.HTTPProvider(MONAD_RPC_URL))

abi = json.loads('[{"inputs":[{"name":"marketId","type":"bytes32"}],"name":"getMarket","outputs":[{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"uint256"},{"name":"","type":"bool"},{"name":"","type":"uint8"}],"stateMutability":"view","type":"function"}]')
turbo = w3.eth.contract(address=Web3.to_checksum_address(TURBO_CONTRACT_ADDRESS), abi=abi)

# Get all market IDs from trades
conn = _conn()
rows = conn.execute("SELECT DISTINCT market_id FROM trades").fetchall()
conn.close()

print(f"Found {len(rows)} markets in trades DB")

for row in rows:
    mid_hex = row["market_id"]
    mid_padded = mid_hex.replace("0x", "").ljust(64, "0")
    mid_bytes = bytes.fromhex(mid_padded)

    mkt = turbo.functions.getMarket(mid_bytes).call()
    strike = mkt[0]
    start_time = mkt[1]
    end_time = mkt[2]
    resolved = mkt[3]
    outcome = "YES" if mkt[4] == 0 else "NO"

    # Save market
    save_market(mid_hex, strike, start_time, end_time)
    print(f"  {mid_hex[:18]}: strike={strike/1e6:.2f} resolved={resolved} outcome={outcome}")

    if resolved:
        resolve_market(mid_hex, outcome, 0)
        print(f"    → Marked as resolved: {outcome}")

print("\nDone! Restart the backend to see updated leaderboard.")
