#!/usr/bin/env python3
import os
import json
import requests
from datetime import datetime, timedelta, timezone
from dotenv import load_dotenv
from difflib import SequenceMatcher
import re

load_dotenv()

KALSHI_API_KEY = os.getenv('KALSHI_API_KEY')
KALSHI_BASE_URL = 'https://api.elections.kalshi.com/trade-api/v2'

def normalize_text(text):
    text = text.lower()
    text = re.sub(r'[^a-z0-9\s]', ' ', text)
    return ' '.join(text.split())

def text_similarity(text1, text2):
    return SequenceMatcher(None, normalize_text(text1), normalize_text(text2)).ratio()

def fetch_polymarket_markets():
    url = "https://gamma-api.polymarket.com/markets"
    now = datetime.now(timezone.utc)
    two_days = now + timedelta(days=2)
    
    response = requests.get(url, params={
        'closed': 'false',
        'limit': 500,
        'end_date_min': now.isoformat(),
        'end_date_max': two_days.isoformat()
    }, timeout=60)
    response.raise_for_status()
    
    processed = []
    for m in response.json():
        if not m.get('active') or m.get('closed') or not m.get('endDate'):
            continue
        
        slug = m.get('slug', '')
        if slug:
            slug_clean = re.sub(r'-\d+$', '', slug)
            url = f"https://polymarket.com/event/{slug_clean}"
        else:
            url = f"https://polymarket.com/market/{m.get('id', '')}"
        
        processed.append({
            'platform': 'Polymarket',
            'id': m.get('id'),
            'question': m.get('question', ''),
            'end_date': m.get('endDate'),
            'url': url
        })
    
    return processed

def fetch_kalshi_markets():
    headers = {'Authorization': f'Bearer {KALSHI_API_KEY}'}
    now = datetime.now(timezone.utc)
    two_days = now + timedelta(days=2)
    
    params = {
        'limit': 200,
        'min_close_ts': int(now.timestamp()),
        'max_close_ts': int(two_days.timestamp())
    }
    
    all_markets = []
    cursor = None
    
    for _ in range(50):
        if cursor:
            params['cursor'] = cursor
        
        response = requests.get(f"{KALSHI_BASE_URL}/markets", headers=headers, params=params, timeout=30)
        response.raise_for_status()
        data = response.json()
        
        all_markets.extend(data.get('markets', []))
        cursor = data.get('cursor')
        if not cursor:
            break
    
    processed = []
    for m in all_markets:
        if m.get('status') not in ['active', 'open'] or not m.get('close_time') or m.get('mve_selected_legs'):
            continue
        
        ticker = m.get('ticker')
        event_ticker = m.get('event_ticker', '')
        url = f"https://kalshi.com/markets/{event_ticker}" if event_ticker else f"https://kalshi.com/markets/{ticker}"
        
        processed.append({
            'platform': 'Kalshi',
            'id': ticker,
            'question': m.get('title', ''),
            'end_date': m.get('close_time'),
            'url': url
        })
    
    return processed

def match_markets(poly_markets, kalshi_markets):
    matches = []
    used_kalshi = set()
    
    for pm in poly_markets:
        best_match = None
        best_score = 0.50
        
        for km in kalshi_markets:
            if km['id'] in used_kalshi:
                continue
            
            score = text_similarity(pm['question'], km['question'])
            if score > best_score:
                best_score = score
                best_match = km
        
        if best_match:
            used_kalshi.add(best_match['id'])
            matches.append({
                'polymarket': pm,
                'kalshi': best_match,
                'similarity': best_score
            })
    
    return matches

def main():
    print("Fetching markets ending in next 48 hours...")
    poly_markets = fetch_polymarket_markets()
    print(f"Polymarket: {len(poly_markets)} markets")
    
    kalshi_markets = fetch_kalshi_markets()
    print(f"Kalshi: {len(kalshi_markets)} markets")
    
    print("\nMatching markets...")
    matches = match_markets(poly_markets, kalshi_markets)
    print(f"Found {len(matches)} matches")
    
    output = {
        'timestamp': datetime.now(timezone.utc).isoformat(),
        'matches': matches
    }
    
    with open('matched_markets.json', 'w') as f:
        json.dump(output, f, indent=2)
    
    print(f"\nSaved {len(matches)} matched markets to matched_markets.json")

if __name__ == '__main__':
    main()
