'use strict';

const {
  PromptSectionRegistry,
  appendPromptManifest,
  buildPromptManifest,
  normalizePromptManifestSection,
  toolCatalogSignature,
} = require('../coding/prompt-section-registry');

function buildRuntimePromptManifest({
  runtimeProfile = {},
  systemPrompt = '',
  userTask = '',
  messages = [],
  tools = [],
  provider = '',
  model = '',
  metadata = {},
  now = () => new Date().toISOString(),
} = {}) {
  const registry = new PromptSectionRegistry({
    provider: provider || runtimeProfile.provider || '',
    model: model || runtimeProfile.model || '',
    now,
  });
  registry.add({
    id: 'stable.system-prompt',
    kind: 'stable',
    source: 'runtime.system',
    content: systemPrompt,
    cacheable: true,
    metadata: {
      runtimeProfile: runtimeProfile.profileId || runtimeProfile.runtimeProfile || '',
      outputContract: runtimeProfile.outputContract || '',
    },
  });
  if (userTask) {
    registry.add({
      id: 'dynamic.user-task',
      kind: 'dynamic',
      source: 'user',
      content: userTask,
      cacheable: false,
      redactionPolicy: 'standard',
    });
  }
  if (Array.isArray(messages) && messages.length) {
    registry.add({
      id: 'dynamic.message-window',
      kind: 'dynamic',
      source: 'runtime.messages',
      content: JSON.stringify(messages.map((message) => ({
        role: message.role,
        contentType: Array.isArray(message.content) ? 'blocks' : typeof message.content,
      }))),
      cacheable: false,
      metadata: { count: messages.length },
    });
  }
  registry.add({
    id: 'dynamic.tool-catalog',
    kind: 'dynamic',
    source: 'tool-registry',
    content: toolCatalogSignature(tools),
    cacheable: false,
    metadata: { count: Array.isArray(tools) ? tools.length : 0 },
  });
  return registry.manifest({
    metadata: {
      runtimeProfile: runtimeProfile.profileId || runtimeProfile.runtimeProfile || '',
      permissionProfile: runtimeProfile.permissionProfile || '',
      persistenceProfile: runtimeProfile.persistenceProfile || '',
      ...metadata,
    },
  });
}

module.exports = {
  PromptSectionRegistry,
  appendPromptManifest,
  buildPromptManifest,
  buildRuntimePromptManifest,
  normalizePromptManifestSection,
  toolCatalogSignature,
};
