"""
FastAPI routes for Saldos Temporales report.

Endpoints:
  POST /generate  – trigger async CSV generation (returns task_id)
  GET  /task/{id} – poll task status
"""
import logging
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from core.database import get_core_db
from core.security import get_current_user
from api.v1.modules.core.tasks_tracking import track_and_dispatch
from .schemas import SaldosFilter

logger = logging.getLogger(__name__)

router = APIRouter(tags=["Reports - Saldos Temporales"])


@router.post(
    "/generate",
    summary="Generate Saldos Temporales CSV (Async)",
    description=(
        "Triggers a background Celery task to generate the Saldos Temporales CSV. "
        "Returns a `task_id` that can be polled via `/task/{task_id}`."
    ),
)
def generate_saldos_report_async(
    filters: SaldosFilter,
    company_id: int = Query(..., description="Company ID"),
    db: Session = Depends(get_core_db),
    current_user: dict = Depends(get_current_user),
):
    """Enqueue the Celery task and return its ID."""
    from .tasks import generate_saldos_temporales_async
    from core.security import validate_access_to_resource

    logger.info(
        f"User {current_user.get('preferred_username', 'unknown')} "
        f"triggering Saldos Temporales report generation"
    )

    # validate_access_to_resource returns the integer tenant_id from DB
    tenant_id = validate_access_to_resource(db, company_id, current_user, ["report.process"])

    # Inject scoping fields (not from the UI body)
    filters.company_id = company_id
    filters.tenant_id = tenant_id

    filter_data = filters.model_dump()
    user_email = current_user.get("email")

    task = track_and_dispatch(
        db=db,
        task=generate_saldos_temporales_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="generate_saldos_temporales_async",
        task_group="reports",
        task_origin="a76/reports/movements/saldos",
        args=[filter_data, user_email],
    )
    return {"task_id": task.id}


@router.get(
    "/task/{task_id}",
    summary="Get Saldos Temporales Task Status",
    description="Poll the status of a background Saldos Temporales generation task.",
)
def get_saldos_task_status(task_id: str):
    """Return current status and (when ready) the result of the Celery task."""
    from celery.result import AsyncResult
    from core.celery_app import celery_app

    task_result = AsyncResult(task_id, app=celery_app)

    response: dict = {
        "task_id": task_id,
        "status": task_result.status,
    }

    if task_result.state == "PROCESSING":
        response["meta"] = task_result.info

    if task_result.ready():
        response["result"] = task_result.result

    return response
