"""
GET /api/v1/tasks/{task_id}

Polling endpoint for both real Celery tasks and synthetic cache-hit
"tasks" (see analyze.py for why cache hits get a synthetic task id —
it keeps the client integration to a single polling pattern regardless
of whether the result came from cache or a fresh computation).

Accepts either a logged-in customer (JWT) or a service API key — same
dual-auth pattern as /analyze (see app/core/dual_auth.py), since this
is the immediate next call a SaaS dashboard user makes after submitting
an analysis.
"""

from celery.result import AsyncResult
from fastapi import APIRouter, Depends

from app.core.dual_auth import AuthContext, get_auth_context
from app.core.exceptions import TaskNotFoundError
from app.core.logging_config import get_logger
from app.schemas.response import ErrorResponse
from app.services.cache_service import cache_service
from app.workers.celery_app import celery_app

router = APIRouter()
logger = get_logger(__name__)


@router.get(
    "/tasks/{task_id}",
    responses={404: {"model": ErrorResponse}},
)
async def get_task_status(task_id: str, auth: AuthContext = Depends(get_auth_context)) -> dict:
    if task_id.startswith("cached-"):
        cached = await cache_service.get(f"task_result:{task_id}")
        if cached is None:
            raise TaskNotFoundError(
                message="This cached result has expired or does not exist. "
                        "Please submit a new analysis request."
            )
        return {"task_id": task_id, "status": "completed", "result": cached, "error": None}

    result = AsyncResult(task_id, app=celery_app)

    if result.state == "PENDING":
        return {"task_id": task_id, "status": "queued", "result": None, "error": None}

    if result.state == "STARTED":
        return {"task_id": task_id, "status": "running", "result": None, "error": None}

    if result.state == "SUCCESS":
        return {"task_id": task_id, "status": "completed", "result": result.result, "error": None}

    if result.state == "FAILURE":
        logger.warning(f"Task {task_id} reported failure state")
        return {
            "task_id": task_id,
            "status": "failed",
            "result": None,
            "error": "Analysis could not be completed. Please try again or contact support "
                     "if the problem persists.",
        }

    return {"task_id": task_id, "status": "running", "result": None, "error": None}