import { readFileSync } from "node:fs";

const sourceCommit = process.argv[2] || "";
const pipelineRunPrefix = process.argv[3] || "";
const namePrefix = pipelineRunPrefix.endsWith("-") ? pipelineRunPrefix : `${pipelineRunPrefix}-`;
const input = JSON.parse(readFileSync(0, "utf8"));

const matches = (Array.isArray(input?.items) ? input.items : [])
  .filter((item) => String(item?.metadata?.name || "").startsWith(namePrefix))
  .filter((item) => pipelineRunSourceCommit(item) === sourceCommit)
  .sort((left, right) => Date.parse(right?.metadata?.creationTimestamp || 0) - Date.parse(left?.metadata?.creationTimestamp || 0));

if (matches.length === 0) {
  process.stderr.write(`current-source-pipelinerun-missing: sourceCommit=${sourceCommit} pipelineRunPrefix=${pipelineRunPrefix}\n`);
  process.exit(2);
}

process.stdout.write(JSON.stringify(matches[0]));

function pipelineRunSourceCommit(item) {
  const labels = item?.metadata?.labels || {};
  const annotations = item?.metadata?.annotations || {};
  const params = Object.fromEntries((Array.isArray(item?.spec?.params) ? item.spec.params : [])
    .filter((param) => typeof param?.name === "string")
    .map((param) => [param.name, typeof param.value === "string" ? param.value : null]));
  return firstString(
    labels["pipelinesascode.tekton.dev/sha"],
    annotations["pipelinesascode.tekton.dev/sha"],
    labels["unidesk.ai/source-commit"],
    annotations["unidesk.ai/source-commit"],
    params.revision,
    params["source-commit"],
    params.source_commit,
  );
}

function firstString(...values) {
  return values.find((value) => typeof value === "string" && value.length > 0) || null;
}
