from fastapi import APIRouter, BackgroundTasks, Query
from .. import backtest, db

router = APIRouter(prefix="/api/lotto/backtest", tags=["backtest"])


@router.get("/track-record")
def track_record():
    return backtest.track_record()


@router.get("/calibration")
def calibration(weeks: int = Query(52, ge=1, le=520)):
    return {"history": db.get_calibration_history(limit=weeks)}


@router.get("/review/{draw_no}")
def review(draw_no: int):
    if db.get_draw(draw_no) is None:
        from fastapi import HTTPException
        raise HTTPException(404, f"no draw {draw_no}")
    return backtest.build_review_payload(draw_no)


@router.post("/run-forward")
def run_forward(
    background_tasks: BackgroundTasks,
    draw_no: int = Query(...),
    k: int = Query(5000, ge=1, le=5000),
    pool_n: int = Query(20000, ge=1000, le=20000),
):
    background_tasks.add_task(backtest.run_forward_purchase, draw_no, k, pool_n)
    return {"ok": True, "queued": True, "draw_no": draw_no}


@router.post("/backfill")
def backfill(background_tasks: BackgroundTasks, batch: int = 50, sample_m: int = 2000):
    background_tasks.add_task(backtest.backfill_calibration, batch, sample_m)
    return {"ok": True, "message": f"backfill 시작 (batch={batch})"}
