#!/bin/sh
set -eu
echo '{"event":"ci-base-image","phase":"plan-artifacts","image":"__HWLAB_CI_TOOLS_IMAGE__","policy":"no-runtime-apk"}'
for tool in node git; do command -v "$tool" >/dev/null 2>&1 || { echo '{"event":"ci-base-image","phase":"plan-artifacts","ok":false,"reason":"missing-tool","tool":"'"$tool"'"}'; exit 31; }; done
cd /workspace/source/repo
ci_node_deps="${HWLAB_CI_NODE_DEPS:-/opt/hwlab-ci-node-deps/node_modules}"
if [ -d "$ci_node_deps/yaml" ] && [ ! -e node_modules/yaml ]; then
  mkdir -p node_modules
  ln -s "$ci_node_deps/yaml" node_modules/yaml
fi
test "$(git rev-parse HEAD)" = "$(params.revision)"
HWLAB_CATALOG_PATH="$(params.catalog-path)" HWLAB_GIT_URL="$(params.git-url)" HWLAB_GIT_READ_URL="$(params.git-read-url)" HWLAB_GITOPS_BRANCH="$(params.gitops-branch)" HWLAB_SERVICES="$(params.services)" node scripts/ci/restore-artifact-catalog.mjs
node scripts/ci-plan.mjs --lane "$(params.lane)" --target-ref HEAD --deploy-config deploy/deploy.yaml --artifact-catalog "$(params.catalog-path)" --registry-prefix "$(params.registry-prefix)" --services "$(params.services)" --verify-reuse-registry > /workspace/source/ci-plan.json
node - <<'NODE'
const fs = require("node:fs");
const plan = JSON.parse(fs.readFileSync("/workspace/source/ci-plan.json", "utf8"));
const selected = String(process.env.HWLAB_SELECTED_SERVICES || "").split(",").map((item) => item.trim()).filter(Boolean);
const allServices = selected.length > 0 ? selected : ["__HWLAB_DEFAULT_SERVICE_IDS__"];
const affected = new Set(plan.affectedServices || []);
const plannedBuildServices = Array.isArray(plan.buildServices) ? new Set(plan.buildServices) : null;
const selectedSet = new Set(selected);
const byService = new Map((plan.services || []).map((service) => [service.serviceId, service]));
const entries = allServices.map((serviceId) => {
  const service = byService.get(serviceId) || {};
  const serviceSelected = selectedSet.has(serviceId);
  const rolloutAffected = serviceSelected && affected.has(serviceId);
  const envReuse = service.runtimeMode === "env-reuse-git-mirror-checkout" || service.envReuse === true;
  const buildRequired = serviceSelected && (plannedBuildServices ? plannedBuildServices.has(serviceId) : (envReuse ? service.envChanged === true : rolloutAffected));
  return {
    serviceId,
    selected: serviceSelected,
    affected: rolloutAffected,
    buildRequired,
    rolloutAffected,
    runtimeMode: service.runtimeMode || "service-image",
    envChanged: service.envChanged ?? null,
    codeChanged: service.codeChanged ?? null
  };
});
for (const entry of entries) {
  fs.writeFileSync("/tekton/results/affected-" + entry.serviceId, entry.affected ? "true" : "false");
  fs.writeFileSync("/tekton/results/build-" + entry.serviceId, entry.buildRequired ? "true" : "false");
}
fs.writeFileSync("/workspace/source/affected-services.json", JSON.stringify({
  sourceCommitId: plan.sourceCommitId,
  affectedServices: plan.affectedServices || [],
  rolloutServices: plan.rolloutServices || plan.affectedServices || [],
  buildServices: plan.buildServices || entries.filter((entry) => entry.buildRequired).map((entry) => entry.serviceId),
  rolloutWithoutImageBuildServices: plan.rolloutWithoutImageBuildServices || [],
  reusedServices: plan.reusedServices || [],
  serviceReusedCount: plan.serviceReusedCount || 0,
  imageBuildSkippedServices: plan.imageBuildSkippedServices || [],
  buildSkippedCount: plan.buildSkippedCount || 0,
  artifactCatalog: plan.artifactCatalog || null,
  envArtifactGroups: plan.envArtifactGroups || [],
  changedPathSummary: plan.changedPathSummary || null,
  ciCdPlan: plan.ciCdPlan || null,
  services: plan.services || [],
  entries
}, null, 2) + String.fromCharCode(10));
console.log(JSON.stringify({ event: "g14-ci-plan", sourceCommitId: plan.sourceCommitId, affectedServices: plan.affectedServices || [], rolloutServices: plan.rolloutServices || plan.affectedServices || [], buildServices: plan.buildServices || [], rolloutWithoutImageBuildServices: plan.rolloutWithoutImageBuildServices || [], reusedServices: plan.reusedServices || [], serviceReusedCount: plan.serviceReusedCount || 0, imageBuildSkippedServices: plan.imageBuildSkippedServices || [], buildSkippedCount: plan.buildSkippedCount || 0, artifactCatalog: plan.artifactCatalog || null, noImageBuildReason: plan.ciCdPlan?.noImageBuildReason || null, envArtifactGroups: plan.envArtifactGroups || [] }));
NODE
