import { createLogger } from '../utils/logger';
import { getContext, updateContext } from '../utils/contextStore';
import { getLlmClient } from '../llm/llmRouter';
import { copywriterPrompt, jsonRepairPrompt } from '../utils/promptTemplates';

const logger = createLogger('copywriter');

export const runCopywriter = async () => {
  logger.start();
  const context = getContext();
  const { spec, agents = {} } = context;

  // Safely access agent outputs with fallbacks
  const frontendOutput = agents.frontendDeveloper?.output || 'No frontend code generated yet';

  const llmClient = getLlmClient();
  const prompt = copywriterPrompt
    .replace('{{spec}}', JSON.stringify(spec, null, 2))
    .replace('{{frontendCode}}', frontendOutput);

  let response = await llmClient.generate(prompt);
  let copy;

  try {
    copy = JSON.parse(response);
  } catch (error) {
    logger.error('Invalid JSON response from LLM. Attempting to repair...');
    const repairPrompt = jsonRepairPrompt.replace('{{invalidJson}}', response);
    response = await llmClient.generate(repairPrompt);
    try {
      copy = JSON.parse(response);
    } catch (error) {
      logger.error('Failed to repair JSON response. Skipping copy generation.');
      return;
    }
  }

  updateContext({ agents: { ...agents, copywriter: { output: copy, completed: true } } });
  logger.stop();
  logger.success('Generated microcopy.');
  return copy;
};
