from typing import Dict, Any
from fastapi import APIRouter, Depends, Body
from sqlalchemy.orm import Session
from celery.result import AsyncResult 
from core.celery_app import celery_app 
from core.database import get_core_db
from core.security import get_current_user, get_tenant_from_token
from api.v1.modules.core.tasks_tracking import track_and_dispatch
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,
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user)
):
    tenant_id = get_tenant_from_token(current_user) or current_user.get("tenant_id")
    task = track_and_dispatch(
        db=db,
        task=generar_transmission_temporal_async,
        tenant_id=int(tenant_id),
        company_id=getattr(request, "company_id", None),
        requested_by_user=current_user.get("preferred_username") or current_user.get("email") or current_user.get("sub"),
        task_name="generar_transmission_temporal_async",
        task_group="reports",
        task_origin="a76/reports/importacion/transmission/temporal/MAINX30",
        args=[request.model_dump(), tenant_id],
    )
    return {"task_id": task.id, "message": "Generación Temporal iniciada"} 
