from fastapi import APIRouter, HTTPException, Query
from typing import List
from app.services.price_simulator import gold_simulator
from app.schemas.schemas import PriceData, MarketDataResponse

router = APIRouter(prefix="/market", tags=["Market Data"])


@router.get("/gold/current", response_model=MarketDataResponse)
async def get_current_gold_price():
    """Get current gold (XAU/USD) market data - simulated live feed"""
    try:
        # Get current simulated price
        current_price = gold_simulator.get_current_price()

        # Generate recent data for 24h high/low calculation
        recent_data = gold_simulator.generate_historical_data(interval="60min", points=24)

        if len(recent_data) > 0:
            # Calculate 24h stats
            high_24h = max(candle.high for candle in recent_data)
            low_24h = min(candle.low for candle in recent_data)
            
            latest = recent_data[-1]
            previous = recent_data[-2] if len(recent_data) > 1 else latest

            change = latest.close - previous.close
            change_percent = (change / previous.close) * 100

            return MarketDataResponse(
                symbol="XAU/USD",
                price=current_price,
                change=change,
                change_percent=change_percent,
                high_24h=high_24h,
                low_24h=low_24h,
                volume=0.0,
            )
        else:
            raise HTTPException(status_code=500, detail="Unable to generate market data")

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/gold/history", response_model=List[PriceData])
async def get_gold_historical_data(
    interval: str = Query("daily", description="Time interval: daily, 1min, 5min, 15min, 30min, 60min"),
    output_size: str = Query("compact", description="compact (100 points) or full (500 points)"),
):
    """Get historical gold (XAU/USD) price data - simulated"""
    try:
        # Determine number of points based on output_size
        points = 500 if output_size == "full" else 100
        
        # Generate historical data using simulator
        data = gold_simulator.generate_historical_data(interval=interval, points=points)

        return data

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/gold/live", response_model=PriceData)
async def get_live_gold_price(
    interval: str = Query("1min", description="Time interval for rounding: 1min, 5min, 15min, 30min, 60min")
):
    """Get latest live gold price tick - simulated real-time feed (no external API calls)"""
    try:
        # Use the simulator to generate a live candle
        live_candle = gold_simulator.get_live_candle(interval=interval)
        return live_candle
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
