import { createHash } from 'node:crypto';
import { PROTOCOL_VERSION, type CommandId, type ExecutorCommand, type WorkerId } from '@platform-modules/chatgpt-orchestrator-protocol';

export type SteeringReason = 'checkpoint' | 'corrective';

export function deliveryCommandId(idempotencyKey: string): CommandId {
  const hex = createHash('sha256').update(`chatgpt-orchestrator:delivery:${idempotencyKey}`).digest('hex');
  const uuid = `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
  return `cmd_${uuid}` as CommandId;
}

export function createSteeringCommand(input: {
  workerId: WorkerId;
  prompt: string;
  reason: SteeringReason;
  idempotencyKey: string;
  deadline?: string;
}): Extract<ExecutorCommand, { type: 'conversation.steer' }> {
  return {
    protocolVersion: PROTOCOL_VERSION,
    commandId: deliveryCommandId(input.idempotencyKey),
    type: 'conversation.steer',
    workerId: input.workerId,
    idempotencyKey: input.idempotencyKey,
    deadline: input.deadline ?? new Date(Date.now() + 2 * 60_000).toISOString(),
    prompt: input.prompt,
    reason: input.reason,
  };
}
