"""
Jobs API Blueprint

This module provides API endpoints for job status polling:
- Get job status
- Get job result

All endpoints require authentication.
"""

from flask import Blueprint

from app.tasks.ai_tasks import get_job_status, get_job_result
from app.utils.response import (
    success_response,
    not_found_response,
    error_response
)
from app.utils.auth import require_auth
from app.utils.logging import get_logger


# Initialize logger
logger = get_logger(__file__)

# Create blueprint
jobs_bp = Blueprint('jobs', __name__)


@jobs_bp.route('/api/v1/jobs/<job_id>/status', methods=['GET'])
@require_auth
def job_status(job_id: str):
    """
    Get the status of an AI job.

    Args:
        job_id: The job ID returned from action submission

    Returns:
        JSON response with job status and result if completed
    """
    try:
        status_info = get_job_status(job_id)

        if not status_info or status_info.get('status') == 'not_found':
            return not_found_response(f"Job not found: {job_id}")

        # If completed, include the result
        if status_info.get('status') == 'completed':
            result = get_job_result(job_id)
            if result:
                status_info['dm_response'] = result.get('dm_response', '')
                status_info['tokens_used'] = result.get('tokens_used', 0)
                status_info['model'] = result.get('model', '')

        logger.debug("Job status retrieved",
                    job_id=job_id,
                    status=status_info.get('status'))

        return success_response(status_info)

    except Exception as e:
        logger.error("Failed to get job status",
                    job_id=job_id,
                    error=str(e),
                    exc_info=True)
        return error_response(
            status=500,
            code="JOB_STATUS_ERROR",
            message="Failed to get job status"
        )
