import type { PromptTemplate, PromptBlock, OutputMode } from '../types';

const OUTPUT_MODE_INSTRUCTIONS: Record<OutputMode, string> = {
  short: 'Răspunde concis, maximum 2-3 paragrafe.',
  'expanded-expert': 'Răspunde detaliat, ca expert în domeniu. Folosește terminologie profesională.',
  'step-by-step': 'Răspunde pas cu pas, cu numerotare clară.',
  'chain-of-thought': 'Gândește cu voce tare. Arată raționamentul pas cu pas înainte de a da răspunsul final.',
  'structured-json': 'Răspunde în format JSON structurat.',
  checklist: 'Răspunde sub formă de checklist cu casete de bifat (- [ ] item).',
};

function interpolateVariables(content: string, values: Record<string, unknown>): string {
  return content.replace(/\{\{(\w+)\}\}/g, (match, key: string) => {
    const val = values[key];
    if (val === undefined || val === null || val === '') return match;
    if (Array.isArray(val)) return val.join(', ');
    return String(val);
  });
}

function shouldIncludeBlock(block: PromptBlock, values: Record<string, unknown>): boolean {
  if (!block.conditional) return true;
  const { variableId, operator, value } = block.conditional;
  const actual = values[variableId];

  switch (operator) {
    case 'truthy': return !!actual;
    case 'falsy': return !actual;
    case 'equals': return String(actual) === value;
    case 'notEquals': return String(actual) !== value;
    default: return true;
  }
}

export function composePrompt(
  template: PromptTemplate,
  values: Record<string, unknown>,
): string {
  const blocks = [...template.blocks]
    .sort((a, b) => a.order - b.order)
    .filter((block) => shouldIncludeBlock(block, values));

  const parts: string[] = [];

  for (const block of blocks) {
    const content = interpolateVariables(block.content, values).trim();
    if (!content) continue;
    parts.push(content);
  }

  // Add output mode instruction
  const modeInstruction = OUTPUT_MODE_INSTRUCTIONS[template.outputMode];
  if (modeInstruction) {
    parts.push(modeInstruction);
  }

  // Add safety blocks if enabled
  if (template.safetyBlocks) {
    const enabledSafety = template.safetyBlocks.filter((s) => s.enabled);
    if (enabledSafety.length > 0) {
      parts.push(enabledSafety.map((s) => s.content).join('\n'));
    }
  }

  return parts.join('\n\n');
}

export function getUnfilledVariables(
  template: PromptTemplate,
  values: Record<string, unknown>,
): string[] {
  return template.variables
    .filter((v) => v.required && (values[v.id] === undefined || values[v.id] === '' || values[v.id] === null))
    .map((v) => v.label);
}
