import json
import yaml


def format_deployment_pipeline(run):
    """
    Format deployment pipeline content.

    Parameters
    ----------
    run : kfp_server_api.models.api_run.ApiRun
        The deployment run.

    Returns
    -------
    dict
        A response formatted with the details of a deployment pipeline.
    """
    experiment_id = run.resource_references[0].name

    workflow_manifest = json.loads(
        run.pipeline_spec.workflow_manifest)

    try:
        template = list(filter(lambda t: t["name"] == "deployment", workflow_manifest["spec"]["templates"]))[0]
        deployment_manifest = yaml.load(template['resource']['manifest'], Loader=yaml.FullLoader)

        name = deployment_manifest["metadata"]["name"]
        deployment_id = deployment_manifest["metadata"]["deploymentId"]

        if "deploymentName" in deployment_manifest["metadata"]:
            name = deployment_manifest["metadata"]["deploymentName"]
        return {
            "experimentId": experiment_id,
            "name": name,
            "deploymentId": deployment_id,
            "status": run.status or "Running",
            "createdAt": run.created_at,
            "runId": run.id
        }
    except (IndexError, KeyError):
        return {}