import uuid
from fastapi import APIRouter, HTTPException, Request, status
from fastapi.responses import Response
from app.security.rate_limit import limiter
from app.security.turnstile import verify_turnstile
from app.services.mt940_parser import MT940Parser
from app.services.camt053_mapper import Camt053Mapper
from app.schemas.api import PlaygroundConvertRequest

router = APIRouter(tags=["playground"])

_parser = MT940Parser()
_mapper = Camt053Mapper()

MAX_MESSAGE_LEN = 8000


@router.post("/playground/convert")
@limiter.limit("8/day")
def playground_convert(request: Request, body: PlaygroundConvertRequest):
    ip = request.client.host if request.client else None
    if not verify_turnstile(body.turnstile_token, ip):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="No se pudo verificar que eres humano. Recarga la página e intenta de nuevo.",
        )

    if len(body.message) > MAX_MESSAGE_LEN:
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=f"Mensaje demasiado largo para el playground (máximo {MAX_MESSAGE_LEN} caracteres). "
                   "Para volúmenes reales, solicita acceso a la API.",
        )

    if body.format not in ("MT940", "MT950"):
        raise HTTPException(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            detail=f"Formato no soportado: {body.format}. Use MT940 o MT950",
        )

    try:
        parsed = _parser.parse(body.message)
    except ValueError as e:
        raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(e))

    message_id = f"DEMO{uuid.uuid4().hex[:8].upper()}"
    xml_output = _mapper.map(parsed, message_id)

    return Response(content=xml_output, media_type="application/xml")
