"""Ingest API endpoints."""

from uuid import UUID
from fastapi import APIRouter, Depends, Header, status
from sqlalchemy.ext.asyncio import AsyncSession

from src.api.deps import get_db, get_running_scenario
from src.schemas.log import LogIngest, LogResponse
from src.services.ingest_service import ingest_service
from src.models.scenario import Scenario

router = APIRouter()


@router.post(
    "/ingest", response_model=LogResponse, status_code=status.HTTP_202_ACCEPTED
)
async def ingest_log(
    log_data: LogIngest,
    scenario: Scenario = Depends(get_running_scenario),
    db: AsyncSession = Depends(get_db),
):
    """
    Ingest a log message for processing.

    - **message**: The log message content
    - **source**: Optional source identifier
    - **X-Scenario-ID**: Header with the scenario UUID
    """
    log_entry = await ingest_service.ingest_log(
        db=db, scenario=scenario, message=log_data.message, source=log_data.source
    )

    return LogResponse(
        id=log_entry.id,
        scenario_id=log_entry.scenario_id,
        received_at=log_entry.received_at,
        message_preview=log_entry.message_preview,
        source=log_entry.source,
        size_bytes=log_entry.size_bytes,
        has_pii=log_entry.has_pii,
        token_count=log_entry.token_count,
        sqs_blocks=log_entry.sqs_blocks,
    )


@router.post("/flush")
async def flush_queue():
    """Force immediate processing of queued messages."""
    return {"status": "flushed", "message": "Processing is now synchronous"}
