from __future__ import annotations

from typing import Annotated

from fastapi import APIRouter, Depends, HTTPException, Query

from ..market import get_gateway
from .auth import require_user

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


@router.get("/snapshot")
async def market_snapshot(_user: Annotated[str, Depends(require_user)]) -> dict:
    gw = get_gateway()
    snap = gw.snapshot_dict()
    # 切换交易所后短时可能尚未对齐 ATM；仍返回结构便于前端展示交易所
    return snap


@router.get("/option-ladder")
async def market_option_ladder(
    _user: Annotated[str, Depends(require_user)],
    wings: int = Query(default=5, ge=1, le=12),
    side: str = Query(default="call", pattern="^(call|put)$"),
    min_hours: float = Query(default=30, ge=1, le=720),
) -> dict:
    """半自动页单边报价：选剩余时长≥min_hours 的最近到期。"""
    gw = get_gateway()
    ladder = getattr(gw, "option_ladder", None)
    if not callable(ladder):
        raise HTTPException(status_code=501, detail="当前会话不支持 option-ladder")
    return ladder(wings=wings, side=side, min_hours=min_hours)


@router.post("/realign")
async def market_realign(_user: Annotated[str, Depends(require_user)]) -> dict:
    """手动重对齐次日到期 ATM 合约（运维/调试用）。"""
    gw = get_gateway()
    try:
        pair = await gw.realign_async()
    except Exception as e:
        raise HTTPException(status_code=502, detail=str(e)) from e
    return {"ok": True, "pair": pair.to_dict() if pair else None, "snapshot": gw.snapshot_dict()}
