import type { Assignment, Run, Worker, WorkerId } from '@platform-modules/chatgpt-orchestrator-protocol';

export const BOOTSTRAP_VERSION = 2 as const;

export interface WorkerPromptContext {
  run: Run;
  worker: Worker;
  assignment: Assignment;
}

function compact(value: string, maxLength = 240): string {
  const text = value.replace(/\s+/g, ' ').trim();
  return text.length <= maxLength ? text : `${text.slice(0, maxLength - 1).trimEnd()}…`;
}

function list(label: string, values: string[]): string {
  return `${label}: ${values.length ? values.join(' | ') : 'none specified'}`;
}

function visibleHeader({ run, worker, assignment }: WorkerPromptContext): string {
  const displayName = worker.displayName ?? run.taskName ?? run.title;
  const rootConversation = run.rootConversationName ?? run.title;
  const summary = worker.taskSummary ?? compact(assignment.objective);
  return `TASK: ${displayName} | ROOT CONVERSATION: ${rootConversation} | SUMMARY: ${compact(summary)}`;
}

function assignmentDisclosure({ worker, assignment }: WorkerPromptContext): string {
  return [
    'OWNER-VISIBLE ASSIGNMENT:',
    `Worker: ${worker.displayName ?? worker.name} (${worker.workerId})`,
    `Objective: ${assignment.objective}`,
    list('Allowed scope', assignment.allowedScope),
    list('Forbidden scope', assignment.forbiddenScope),
    list('Acceptance criteria', assignment.acceptanceCriteria),
  ].join('\n');
}

function lifecycleContract(): string {
  return [
    'Before ending your work:',
    '- call worker.complete if the entire assignment and acceptance gates are finished;',
    '- call worker.fail if the assignment has irrecoverably failed;',
    '- call worker.await_human only when genuine human input or approval is required;',
    '- call worker.await_dependency only when an external dependency prevents further progress;',
    '- otherwise leave the worker active.',
    '',
    'End every response with exactly one continuation-state block:',
    '<continuation-state>',
    'status: working | complete | blocked',
    'summary: <brief material change this response>',
    'current: <precise current assignment state>',
    'next: <exact next unfinished action, or none>',
    '</continuation-state>',
  ].join('\n');
}

export function workerBootstrap(context: WorkerPromptContext | WorkerId): string {
  if (typeof context === 'string') {
    return [
      `You are an orchestrated worker. Attach to worker ${context} using the ChatGPT Orchestrator MCP and retrieve the authoritative assignment before acting. Perform the assignment normally and communicate material progress through the orchestrator.`,
      '',
      lifecycleContract(),
    ].join('\n');
  }

  return [
    visibleHeader(context),
    '',
    assignmentDisclosure(context),
    '',
    `EXECUTION: You are an orchestrated worker. Attach to worker ${context.worker.workerId} using the ChatGPT Orchestrator MCP, retrieve the authoritative assignment, verify it matches the owner-visible assignment above, execute it to completion, communicate through the orchestrator, and call worker.complete or worker.fail before ending your task. Do not perform work outside the displayed assignment or scope.`,
    '',
    lifecycleContract(),
  ].join('\n');
}

export function workerFollowupPrompt(context: WorkerPromptContext): string {
  return [
    visibleHeader(context),
    '',
    assignmentDisclosure(context),
    '',
    `EXECUTION: New orchestrator work is available for ${context.worker.workerId}. Attach to this same worker using the ChatGPT Orchestrator MCP, retrieve the authoritative current assignment, verify it matches the owner-visible assignment above, and continue until the worker is terminal. Do not perform work outside the displayed assignment or scope.`,
    '',
    lifecycleContract(),
  ].join('\n');
}
