import { createHash } from "node:crypto";

export interface GiteaRemotePayloads {
  manifest: string;
  repositories: string;
  hookTopology: string;
  statusEvaluator: string;
}

interface GiteaRemotePayloadFile {
  role: keyof GiteaRemotePayloads;
  name: string;
  value: string;
}

const payloadFiles = (payloads: GiteaRemotePayloads): GiteaRemotePayloadFile[] => [
  { role: "manifest", name: "gitea.k8s.yaml", value: payloads.manifest },
  { role: "repositories", name: "repos.json", value: payloads.repositories },
  { role: "hookTopology", name: "hook-topology.json", value: payloads.hookTopology },
  { role: "statusEvaluator", name: "platform_infra_gitea_status_evaluator.py", value: payloads.statusEvaluator },
];

function payloadMarker(file: GiteaRemotePayloadFile): string {
  return `__UNIDESK_GITEA_${file.role.toUpperCase()}_STDIN_PAYLOAD__`;
}

export function renderGiteaRemotePayloadMaterializer(payloads: GiteaRemotePayloads): string {
  const writes = payloadFiles(payloads).map((file) => {
    const encoded = Buffer.from(file.value, "utf8").toString("base64");
    const marker = payloadMarker(file);
    return [
      `  if ! base64 -d >"$unidesk_gitea_payload_dir/${file.name}" <<'${marker}'`,
      encoded,
      marker,
      "  then",
      "    return 1",
      "  fi",
    ].join("\n");
  });
  return [
    "unidesk_gitea_materialize_payloads() {",
    "  unidesk_gitea_payload_dir=$1",
    "  umask 077",
    ...writes,
    "}",
  ].join("\n");
}

export function summarizeGiteaRemotePayloads(payloads: GiteaRemotePayloads): Record<string, unknown> {
  const files = payloadFiles(payloads).map((file) => ({
    role: file.role,
    bytes: Buffer.byteLength(file.value, "utf8"),
    sha256: `sha256:${createHash("sha256").update(file.value).digest("hex").slice(0, 16)}`,
  }));
  return {
    kind: "trans-stdin-file-envelope",
    materialization: "target-private-tmpdir",
    totalBytes: files.reduce((total, file) => total + file.bytes, 0),
    files,
    valuesPrinted: false,
  };
}
