
from typing import Dict, Any
from fastapi import APIRouter, Depends, Query
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, validate_access_to_resource
from api.v1.modules.core.tasks_tracking import track_and_dispatch
from .task import generar_pdf_aviso_consolidado_exp_async

router = APIRouter()

@router.get("/tasks/{task_id}")
async def get_task_status(
    task_id: str,
    current_user: Dict[str, Any] = Depends(get_current_user),
    db: Session = Depends(get_core_db)
):
    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':
        response["info"] = task_result.info

    return response

@router.post("/{invoice_id}/download-async")
async def trigger_descarga_aviso_consolidado_exp(
    invoice_id: int,
    company_id: int = Query(..., description="ID de la empresa"),
    current_user: Dict[str, Any] = Depends(get_current_user),
    db: Session = Depends(get_core_db)
):
    tenant_id = validate_access_to_resource(db, company_id, current_user)
    task = track_and_dispatch(
        db=db,
        task=generar_pdf_aviso_consolidado_exp_async,
        tenant_id=tenant_id,
        company_id=company_id,
        requested_by_user=current_user.get("preferred_username") or current_user.get("email") or current_user.get("sub"),
        task_name="generar_pdf_aviso_consolidado_exp_async",
        task_group="reports",
        task_origin="a76/reports/exportacion/aviso_consolidado",
        args=[invoice_id, company_id],
    )
    return {"task_id": task.id, "message": "Generación iniciada"} 
