from typing import Any

from app.core.celery_app import celery_app
from app.dependencies import get_ingest_job_repository
from app.schemas.ingest_job import IngestJobResponse, SubmitIngestJobRequest
from fastapi import APIRouter, Depends

from packages.application import SubmitIngestJobCommand, SubmitIngestJobUseCase

router = APIRouter()


@router.get("/{job_id}", response_model=IngestJobResponse)
def get_ingest_job(
    job_id: str,
    ingest_job_repository: Any = Depends(get_ingest_job_repository),
) -> IngestJobResponse:
    job = ingest_job_repository.get(job_id)
    if job is None:
        raise ValueError(f"IngestJob {job_id} not found")
    return IngestJobResponse(
        id=job.id,
        project_id=job.project_id,
        library_id=job.library_id,
        storage_key=job.storage_key,
        status=job.status.value,
        error_message=job.error_message,
        result_asset_id=job.result_asset_id,
    )


@router.post("", response_model=IngestJobResponse)
def submit_ingest_job(
    request: SubmitIngestJobRequest,
    ingest_job_repository: Any = Depends(get_ingest_job_repository),
) -> IngestJobResponse:
    use_case = SubmitIngestJobUseCase(ingest_job_repository)
    job = use_case.execute(
        SubmitIngestJobCommand(
            project_id=request.project_id,
            library_id=request.library_id,
            storage_key=request.storage_key,
        )
    )

    celery_app.send_task("worker.ingest_asset", args=[job.id])

    return IngestJobResponse(
        id=job.id,
        project_id=job.project_id,
        library_id=job.library_id,
        storage_key=job.storage_key,
        status=job.status.value,
        error_message=job.error_message,
        result_asset_id=job.result_asset_id,
    )
