import logging
from fastapi import APIRouter, HTTPException, Depends, status

from mini_videorag.temporal.api.schemas.workflows import (
    StartWorkflowRequest,
    StartWorkflowResponse,
    WorkflowProgressResponse,
    WorkflowResultResponse,
)
from mini_videorag.temporal.api.services import WorkflowService
from mini_videorag.temporal.api.dependencies import get_workflow_service

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/workflows", tags=["Workflows"])


@router.post(
    "/analyze",
    response_model=StartWorkflowResponse,
    summary="Start video analysis workflow",
    description="""
    Start a Temporal workflow to analyze a video using the configured processors.

    The workflow executes all processors defined in config/video_rag_config.yml
    in dependency order (DAG). This is asynchronous - the request returns immediately
    with a workflow_id that you can use to track progress.

    Example:
    ```json
    {
      "video_path": "s3://videos/myvideo.mp4",
      "video_id": "video_123",
      "processor_kwargs": {"num_frames": 10}
    }
    ```

    Then query progress:
    - GET /workflows/{workflow_id}/progress
    - GET /workflows/{workflow_id}/result
    """,
)
async def start_workflow(
    request: StartWorkflowRequest,
    service: WorkflowService = Depends(get_workflow_service),
):
    """Start a video processing workflow."""
    try:
        result = await service.start_video_pipeline(
            request.video_path, request.video_id, request.processor_kwargs
        )
        return StartWorkflowResponse(**result)
    except Exception as e:
        logger.error(f"Failed to start workflow: {e}", exc_info=True)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to start workflow: {str(e)}",
        ) from e


@router.get(
    "/{workflow_id}/progress",
    response_model=WorkflowProgressResponse,
    summary="Get workflow progress",
    description="Query the current progress of a running workflow.",
)
async def get_workflow_progress(
    workflow_id: str,
    service: WorkflowService = Depends(get_workflow_service),
):
    """Get workflow progress."""
    try:
        result = await service.get_workflow_progress(workflow_id)
        return WorkflowProgressResponse(**result)
    except ValueError as e:
        logger.error(f"Invalid workflow ID {workflow_id}: {e}")
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e),
        ) from e
    except TimeoutError as e:
        logger.error(f"Workflow {workflow_id} timed out: {e}")
        raise HTTPException(
            status_code=status.HTTP_504_GATEWAY_TIMEOUT,
            detail=str(e),
        ) from e
    except Exception as e:
        logger.error(
            f"Unexpected error getting workflow progress for {workflow_id}: {e}", exc_info=True
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"Failed to get workflow progress: {str(e)}",
        ) from e


@router.get(
    "/{workflow_id}/result",
    response_model=WorkflowResultResponse,
    summary="Get workflow result",
    description="Get the final result of a completed workflow.",
)
async def get_workflow_result(
    workflow_id: str,
    service: WorkflowService = Depends(get_workflow_service),
):
    """Get workflow result."""
    try:
        result = await service.get_workflow_result(workflow_id)
        return WorkflowResultResponse(**result)
    except Exception as e:
        logger.error(f"Failed to get workflow result: {e}")
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Workflow not found: {str(e)}",
        ) from e
