# retoor <retoor@molodetz.nl>

import logging

from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse

from devplacepy.services.jobs import queue
from devplacepy.schemas import ForkJobOut
from devplacepy.utils import not_found

logger = logging.getLogger(__name__)
router = APIRouter()


def _status_payload(job: dict) -> dict:
    result = job.get("result", {})
    done = job.get("status") == queue.DONE
    return {
        "uid": job.get("uid", ""),
        "kind": job.get("kind", ""),
        "status": job.get("status", ""),
        "preferred_name": job.get("preferred_name"),
        "project_uid": result.get("project_uid") if done else None,
        "project_url": result.get("project_url") if done else None,
        "source_project_uid": result.get("source_project_uid") if done else None,
        "error": job.get("error") or None,
        "item_count": int(job.get("item_count") or 0),
        "created_at": job.get("created_at"),
        "completed_at": job.get("completed_at") or None,
    }


@router.get("/{uid}")
async def fork_status(request: Request, uid: str):
    job = queue.get_job(uid)
    if not job or job.get("kind") != "fork":
        raise not_found("Job not found")
    return JSONResponse(
        ForkJobOut.model_validate(_status_payload(job)).model_dump(mode="json")
    )
