
from fastapi import APIRouter, Depends, BackgroundTasks, HTTPException
from fastapi.responses import JSONResponse, Response
from sqlalchemy.orm import Session
from typing import Dict, Any

from core.database import get_core_db as get_db
from core.security import get_current_user, validate_access_to_resource
from api.v1.modules.core.tasks_tracking import track_and_dispatch
from .service import FIFOAssignmentService
from .task import generate_descarga_pdf_task # FORCE RELOAD
from celery.result import AsyncResult

router = APIRouter()

@router.post("/fifo-assign/{invoice_id}")
def run_fifo_assignment(
    invoice_id: int,
    db: Session = Depends(get_db),
    current_user: Any = Depends(get_current_user),
):
    """
    Executes FIFO (PEPS) calculation for an Export Invoice.
    Returns the calculated discharges in JSON format.
    """
    service = FIFOAssignmentService()
    try:
        discharges = service.calculate_fifo(db, invoice_id)
        return {
            "invoice_id": invoice_id,
            "total_discharges": len(discharges),
            "discharges": discharges
        }
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Error calculating FIFO: {str(e)}"
        )

@router.post("/{invoice_id}/download-async")
async def trigger_descarga_generation(
    invoice_id: int,
    company_id: int,
    db: Session = Depends(get_db),
    current_user: Any = Depends(get_current_user)
):
    """
    Inicia la generación del reporte de Descarga PEPS en segundo plano (Celery).
    Retorna el task_id para polling.
    """
    try:
        tenant_id = validate_access_to_resource(db, company_id, current_user)
        task = track_and_dispatch(
            db=db,
            task=generate_descarga_pdf_task,
            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="generate_descarga_pdf_task",
            task_group="reports",
            task_origin="a76/reports/exportacion/descargo",
            args=[invoice_id, company_id],
        )
        return {"task_id": task.id, "status": "processing"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/tasks/{task_id}")
async def get_task_status(task_id: str, current_user: Any = Depends(get_current_user)):
    """
    Consulta el estado de la tarea de Celery.
    """
    task_result = AsyncResult(task_id)
    
    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
