from fastapi import APIRouter, Depends, BackgroundTasks
from sqlalchemy.orm import Session
from core.database import get_core_db
from .schemas import WinsaaiGenerationRequest, WinsaaiResponse
from .task import generate_winsaai_task
from core.celery_app import celery_app
from celery.result import AsyncResult
from typing import Dict, Any
import logging
from core.security import get_current_user, get_tenant_from_token
from api.v1.modules.core.tasks_tracking import track_and_dispatch

logger = logging.getLogger(__name__)

router = APIRouter(tags=["WINSAAI"])

@router.post("/generate", response_model=WinsaaiResponse)
async def trigger_winsaai_generation(
    request: WinsaaiGenerationRequest,
    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=generate_winsaai_task,
        tenant_id=int(tenant_id),
        requested_by_user=current_user.get("preferred_username") or current_user.get("email") or current_user.get("sub"),
        task_name="generate_winsaai_task",
        task_group="reports",
        task_origin="a76/reports/importacion/winsaai/invoices",
        args=[request.invoice_ids, request.is_temporal],
    )
    return WinsaaiResponse(
        task_id=task.id,
        status="PENDING",
        message="WINSAAI generation task started"
    )

@router.get("/status/{task_id}")
async def get_task_status(task_id: str):
    logger.info(f"Polling status for WINSAAI task {task_id}")
    task_result = AsyncResult(task_id, app=celery_app)
    
    try:
        state = task_result.state
        info = task_result.info
        logger.debug(f"Task {task_id} state: {state}, info: {info}")
    except Exception as e:
        logger.error(f"Error polling task {task_id}: {str(e)}")
        return {"task_id": task_id, "state": "FAILURE", "result": str(e), "info": None}

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

    if state == 'FAILURE':
        # Safely try to get result, but handle cases where it can't be deserialized
        try:
            # result = task_result.result # This might trigger the ValueError
            # Better: if it's FAILURE, just report it as failed and maybe look into info/meta
            response["result"] = "Task failed. Check worker logs for details."
            if isinstance(info, dict) and 'error' in info:
                 response["result"] = info['error']
        except Exception:
            response["result"] = "Task failed (error reading exception details)"
    elif state == 'SUCCESS':
        response["result"] = task_result.result
    elif state in ['PROCESSING', 'PROGRESS']:
        response["info"] = info

    return response

@router.get("/download/{task_id}")
async def download_winsaai_file(task_id: str):
    res = AsyncResult(task_id)
    if not res.ready():
        return {"error": "Task not ready"}
    
    result = res.result
    if isinstance(result, dict) and "filepath" in result:
        from fastapi.responses import FileResponse
        return FileResponse(
            path=result["filepath"],
            filename=result["filename"],
            media_type="text/plain"
        )
    return {"error": "File not found"}
