import { type HwlabRuntimeLaneSpec, hwlabRuntimeLaneConfigPath } from "../hwlab-node-lanes";
import { pipelineProvenanceAnnotations, type PipelineProvenanceContract } from "../pipeline-provenance";
import { stableJsonSha256 } from "../stable-json";

export interface HwlabRuntimePipelineProvenance extends PipelineProvenanceContract {
  readonly renderer: "hwlab-runtime-lane";
  readonly mode: "remote-pipeline-annotation";
}

export function hwlabRuntimePipelineProvenance(spec: HwlabRuntimeLaneSpec): HwlabRuntimePipelineProvenance {
  const declared = spec.pipelineProvenance;
  if (declared === undefined) {
    throw new Error(`${hwlabRuntimeLaneConfigPath()}#lanes.${spec.lane}.targets.${spec.nodeId}.pipelineProvenance is required`);
  }
  const expectedConfigRef = `${hwlabRuntimeLaneConfigPath()}#lanes.${spec.lane}.targets.${spec.nodeId}`;
  if (declared.configRef !== expectedConfigRef) {
    throw new Error(`pipelineProvenance.configRef must equal selected target owner ${expectedConfigRef}`);
  }
  return {
    configRef: declared.configRef,
    effectiveConfigSha256: stableJsonSha256(spec),
    renderer: declared.renderer,
    mode: declared.mode,
  };
}

export function hwlabRuntimePipelineProvenanceAnnotations(spec: HwlabRuntimeLaneSpec): Record<string, string> {
  return pipelineProvenanceAnnotations(hwlabRuntimePipelineProvenance(spec));
}
