"""Translate cloud API job format to edge agent job format."""

from __future__ import annotations

from typing import Any


def cloud_job_to_edge_fields(cloud_job: dict[str, Any]) -> dict[str, Any]:
    """Convert a cloud API job dict to fields for INSERT into the edge jobs table.

    Cloud job fields (from clusters_store.create_cluster_job):
        job_id, cluster_id, tenant_id, job_kind, image, command, args, env,
        input_payload, params, orchestration (num_gpus, launcher, timeout_seconds)

    Edge job fields (from db.py SCHEMA):
        job_id, user_id, image, command, args, env, job_type, priority,
        num_gpus, timeout_seconds, origin, upstream_job_id, metadata
    """
    orchestration = cloud_job.get("orchestration") or {}
    params = cloud_job.get("params") or {}

    return {
        "user_id": cloud_job.get("tenant_id", "upstream"),
        "name": f"upstream:{cloud_job.get('job_kind', 'generic')}:{cloud_job['job_id']}",
        "image": cloud_job.get("image", ""),
        "command": cloud_job.get("command") or [],
        "args": cloud_job.get("args") or [],
        "env": cloud_job.get("env") or {},
        "job_type": cloud_job.get("job_kind", "generic"),
        "priority": 5,
        "num_gpus": int(orchestration.get("num_gpus", 1)),
        "gpu_mem_required_mb": 0,
        "timeout_seconds": int(orchestration.get("timeout_seconds", 3600)),
        "origin": "upstream",
        "upstream_job_id": cloud_job["job_id"],
        "metadata": {
            "cloud_origin": cloud_job.get("origin", "api"),
            "model_ref": cloud_job.get("model_ref"),
            "params": params,
            "input_payload": cloud_job.get("input_payload"),
        },
    }
