from typing import Dict, Any
from fastapi import APIRouter, Depends, Body
from celery.result import AsyncResult 
from core.celery_app import celery_app 
from core.security import get_current_user
from .task import generar_transmission_temporal_async
from .schemas import Mainx30GenerationRequest

router = APIRouter()

@router.get("/tasks/{task_id}")
async def get_task_status(
    task_id: str,
    current_user: Dict[str, Any] = Depends(get_current_user)
):
    task_result = AsyncResult(task_id, app=celery_app)

    response = {
        "task_id": task_id,
        "state": task_result.state,
        "result": None,
        "info": None
    }

    if task_result.state == 'FAILURE':
        response["result"] = str(task_result.result)
    elif task_result.state == 'SUCCESS':
        response["result"] = task_result.result
    elif task_result.state == 'PROCESSING':
        # Ensure info is serializable
        response["info"] = task_result.info

    return response

@router.post("/generate")
async def trigger_generation(
    request: Mainx30GenerationRequest,
    current_user: Dict[str, Any] = Depends(get_current_user)
):
    tenant_id = current_user.get("tenant_id")
    # Pass request as dict to Celery task
    task = generar_transmission_temporal_async.delay(request.model_dump(), tenant_id)
    return {"task_id": task.id, "message": "Generación Temporal iniciada"} 
