from typing import Any, Dict

from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

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 process_export_invoice_task

router = APIRouter()


@router.post("/invoices/{invoice_id}/process")
def trigger_invoice_process(
    invoice_id: int,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: Dict[str, Any] = Depends(get_current_user),
):
    """
    Inicia el procesamiento de una factura de exportación como tarea Celery.
    Retorna el task_id para hacer polling del progreso.
    """
    tenant_id = validate_access_to_resource(db, company_id, current_user)

    username = current_user.get("preferred_username") or current_user.get("email") or current_user.get("sub") or "SYSTEM"

    task = track_and_dispatch(
        db=db,
        task=process_export_invoice_task,
        tenant_id=tenant_id,
        company_id=company_id,
        requested_by_user=username,
        task_name="process_export_invoice_task",
        task_group="invoices",
        task_origin="a76/invoices/exports/process",
        args=[invoice_id, str(tenant_id), str(company_id), username],
    )

    return {"task_id": task.id}


@router.get("/invoices/process/{task_id}/status")
def get_invoice_process_status(task_id: str):
    """
    Consulta el estado de progreso de una tarea de procesamiento de factura.

    Retorna:
      - state: 'PROCESSING' | 'SUCCESS' | 'FAILURE'
      - info: { current: int, status: str }  (cuando state == 'PROCESSING')
      - result: dict                          (cuando state == 'SUCCESS' o 'FAILURE')
    """
    task_result = celery_app.AsyncResult(task_id)

    if task_result.state in ("PENDING", "STARTED"):
        return {
            "state": "PROCESSING",
            "info": {"current": 0, "status": "Iniciando..."},
        }

    if task_result.state == "PROGRESS":
        return {
            "state": "PROCESSING",
            "info": task_result.info or {"current": 0, "status": "Procesando..."},
        }

    if task_result.state == "SUCCESS":
        return {
            "state": "SUCCESS",
            "result": task_result.result,
        }

    error_info = task_result.result
    if isinstance(error_info, Exception):
        error_msg = str(error_info)
    else:
        error_msg = str(error_info) if error_info else "Error desconocido"

    return {
        "state": "FAILURE",
        "result": error_msg,
    }
