from __future__ import annotations

import json

from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession

from api.database import get_session
from api.schemas.consistency_sweep import (
    ConsistencySweepRemoteAllGenerate,
    ConsistencySweepRemoteAllRun,
)
from api.services.consistency_sweep import run_remote_all_sweep

router = APIRouter(prefix="/consistency/sweep", tags=["consistency"])


@router.post(
    "/remote-all",
    response_model=ConsistencySweepRemoteAllRun,
    status_code=status.HTTP_201_CREATED,
)
async def sweep_remote_all(
    body: ConsistencySweepRemoteAllGenerate,
    session: AsyncSession = Depends(get_session),
) -> ConsistencySweepRemoteAllRun:
    try:
        return await run_remote_all_sweep(
            session,
            max_seconds=body.max_seconds,
            source=body.source,
        )
    except json.JSONDecodeError as exc:
        raise HTTPException(
            status_code=500,
            detail=f"Consistency sweep returned invalid JSON: {exc}",
        ) from exc