import requests
from datetime import datetime, timedelta
from typing import Optional, List, Dict
import json


def get_price_history(
    token_id: str,
    start_ts: Optional[int] = None,
    end_ts: Optional[int] = None,
    interval: str = "1h"
) -> Dict:
    """
    Get price history for a Polymarket token.
    
    Args:
        token_id: The CLOB token ID from the market data
        start_ts: Start timestamp (Unix epoch). If None, defaults to 30 days ago
        end_ts: End timestamp (Unix epoch). If None, defaults to now
        interval: Time interval - options: '1m', '5m', '1h', '6h', '1d', 'max', 'all'
    
    Returns:
        Dict with 'history' key containing list of price points
    """
    base_url = "https://clob.polymarket.com/prices-history"
    
    # Default to last 30 days if not specified
    if end_ts is None:
        end_ts = int(datetime.now().timestamp())
    if start_ts is None:
        start_ts = int((datetime.now() - timedelta(days=30)).timestamp())
    
    params = {
        "market": token_id,
        "startTs": start_ts,
        "endTs": end_ts,
        "interval": interval
    }
    
    response = requests.get(base_url, params=params)
    response.raise_for_status()
    return response.json()


def get_market_price_history(
    market_data: Dict,
    outcome_index: int = 0,
    start_ts: Optional[int] = None,
    end_ts: Optional[int] = None,
    interval: str = "1h"
) -> Dict:
    """
    Get price history for a specific outcome in a market.
    
    Args:
        market_data: Market data dict from markets.json
        outcome_index: Which outcome to get (0 for first, 1 for second, etc.)
        start_ts: Start timestamp (Unix epoch)
        end_ts: End timestamp (Unix epoch)
        interval: Time interval
    
    Returns:
        Dict with 'history' key containing list of price points
    """
    clob_token_ids = json.loads(market_data.get("clobTokenIds", "[]"))
    
    if not clob_token_ids or outcome_index >= len(clob_token_ids):
        raise ValueError(f"Invalid outcome_index {outcome_index} for market")
    
    token_id = clob_token_ids[outcome_index]
    return get_price_history(token_id, start_ts, end_ts, interval)


def get_all_outcomes_history(
    market_data: Dict,
    start_ts: Optional[int] = None,
    end_ts: Optional[int] = None,
    interval: str = "1h"
) -> List[Dict]:
    """
    Get price history for all outcomes in a market.
    
    Args:
        market_data: Market data dict from markets.json
        start_ts: Start timestamp (Unix epoch)
        end_ts: End timestamp (Unix epoch)
        interval: Time interval
    
    Returns:
        List of dicts, one per outcome, each with 'outcome', 'token_id', and 'history'
    """
    clob_token_ids = json.loads(market_data.get("clobTokenIds", "[]"))
    outcomes = json.loads(market_data.get("outcomes", "[]"))
    
    results = []
    for i, (token_id, outcome) in enumerate(zip(clob_token_ids, outcomes)):
        history = get_price_history(token_id, start_ts, end_ts, interval)
        results.append({
            "outcome": outcome,
            "token_id": token_id,
            "history": history.get("history", [])
        })
    
    return results


if __name__ == "__main__":
    # Example usage
    with open("markets.json", "r") as f:
        markets = json.load(f)
    
    # Get first market
    market = markets[0]
    print(f"Market: {market['question']}")
    print(f"Outcomes: {market['outcomes']}")
    
    # Get history for first outcome (last 7 days)
    end_ts = int(datetime.now().timestamp())
    start_ts = int((datetime.now() - timedelta(days=7)).timestamp())
    
    try:
        history = get_market_price_history(market, outcome_index=0, start_ts=start_ts, end_ts=end_ts, interval="1h")
        print(f"\nPrice history points: {len(history.get('history', []))}")
        if history.get('history'):
            print(f"First point: {history['history'][0]}")
            print(f"Last point: {history['history'][-1]}")
    except Exception as e:
        print(f"Error: {e}")
