import chalk from 'chalk';

const agentStyles = {
  productManager: chalk.bold.blue,
  frontendDeveloper: chalk.green,
  backendDeveloper: chalk.yellow.italic,
  qaEngineer: chalk.red.underline,
  documentationAgent: chalk.cyan,
  fullstackIntegrator: chalk.magenta,
  infraEngineer: chalk.gray,
  securityEngineer: chalk.yellow,
  uxDesigner: chalk.blue,
  copywriter: chalk.green,
  releaseManager: chalk.magenta.bold,
  aiPromptEngineer: chalk.blue.italic,
  dataEngineer: chalk.yellow,
  orchestratorAgent: chalk.bold.magenta,
  voiceNarratorAgent: chalk.italic.gray,
  reviewerAgent: chalk.bold.yellow,
  assumptionChallenger: chalk.bold.red,
  userEmpathyAgent: chalk.bold.green,
};

type AgentName = keyof typeof agentStyles;

const log = (agentName: AgentName, message: string, icon: string = '📝') => {
  const styledMessage = `${agentStyles[agentName](`[${agentName}]`)} ${icon} ${message}`;
  console.log(styledMessage);
  // logToContext(styledMessage); // This will be handled by the orchestrator
};

const spinner = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
const agentIntervals = new Map<AgentName, NodeJS.Timeout>();

const startThinking = (agentName: AgentName) => {
  stopThinking(agentName); // Ensure no old interval is running
  
  let i = 0;
  const interval = setInterval(() => {
    i = (i + 1) % spinner.length;
    process.stdout.write(`\r${agentStyles[agentName](`[${agentName}]`)} ${spinner[i]} is thinking...`);
  }, 100);
  
  agentIntervals.set(agentName, interval);
};

const stopThinking = (agentName: AgentName) => {
  const interval = agentIntervals.get(agentName);
  if (interval) {
    clearInterval(interval);
    agentIntervals.delete(agentName);
    process.stdout.write('\r' + ' '.repeat(50) + '\r'); // Clear the line
  }
};

export const createLogger = (agentName: AgentName) => ({
  log: (message: string) => log(agentName, message),
  start: () => startThinking(agentName),
  stop: () => stopThinking(agentName),
  info: (message: string) => log(agentName, chalk.white(message), 'ℹ️'),
  success: (message: string) => log(agentName, chalk.greenBright(message), '✅'),
  error: (message: string) => log(agentName, chalk.redBright(message), '❌'),
  warn: (message: string) => log(agentName, chalk.yellowBright(message), '⚠️'),
  debug: (message: string) => {
    if (process.env.DEBUG === 'true') {
      log(agentName, chalk.gray(message), '🐛');
    }
  },
});

export const orchestratorLogger = createLogger('orchestratorAgent');

const cleanupAllIntervals = () => {
  agentIntervals.forEach((_, agentName) => {
    stopThinking(agentName);
  });
};

process.on('exit', cleanupAllIntervals);
process.on('SIGINT', () => {
  cleanupAllIntervals();
  process.exit(0);
});
process.on('SIGTERM', () => {
  cleanupAllIntervals();
  process.exit(0);
});
