from typing import Any

from app.core.celery_app import celery_app
from app.dependencies import get_classification_job_repository
from app.schemas.classification_job import (
    ClassificationJobResponse,
    SubmitClassificationJobRequest,
)
from fastapi import APIRouter, Depends, HTTPException

from packages.application import (
    SubmitClassificationJobCommand,
    SubmitClassificationJobUseCase,
)

router = APIRouter()


@router.get("/{job_id}", response_model=ClassificationJobResponse)
def get_classification_job(
    job_id: str,
    classification_job_repository: Any = Depends(get_classification_job_repository),
) -> ClassificationJobResponse:
    job = classification_job_repository.get(job_id)
    if job is None:
        raise HTTPException(status_code=404, detail=f"ClassificationJob {job_id} not found")
    return ClassificationJobResponse(
        id=job.id,
        project_id=job.project_id,
        asset_id=job.asset_id,
        status=job.status,
        classification=job.classification,
        confidence=job.confidence,
        error_message=job.error_message,
    )


@router.post("", response_model=ClassificationJobResponse)
def submit_classification_job(
    request: SubmitClassificationJobRequest,
    classification_job_repository: Any = Depends(get_classification_job_repository),
) -> ClassificationJobResponse:
    use_case = SubmitClassificationJobUseCase(classification_job_repository)
    job = use_case.execute(
        SubmitClassificationJobCommand(
            project_id=request.project_id,
            asset_id=request.asset_id,
        )
    )
    celery_app.send_task("worker.classify_asset", args=[job.id])
    return ClassificationJobResponse(
        id=job.id,
        project_id=job.project_id,
        asset_id=job.asset_id,
        status=job.status,
        classification=job.classification,
        confidence=job.confidence,
        error_message=job.error_message,
    )
