import { writeFileSync, readFileSync, existsSync, mkdirSync } from 'fs';
import { dirname } from 'path';
import { EnhancementLogEntry } from './types';

export class EnhancementLogger {
  private static instance: EnhancementLogger | null = null;
  private logFilePath: string | null = null;
  private isEnabled: boolean = false;

  private constructor() {
    const enhLogPath = process.env['ENH_LOG'];

    if (enhLogPath) {
      this.logFilePath = enhLogPath;
      this.isEnabled = true;
      this.initializeLogFile();
    }
  }

  static getInstance(): EnhancementLogger {
    if (!EnhancementLogger.instance) {
      EnhancementLogger.instance = new EnhancementLogger();
    }
    return EnhancementLogger.instance;
  }

  private initializeLogFile(): void {
    if (!this.logFilePath) return;

    try {
      // Ensure directory exists
      const dir = dirname(this.logFilePath);
      if (!existsSync(dir)) {
        mkdirSync(dir, { recursive: true });
      }

      // Reset/clear the log file on service start
      writeFileSync(this.logFilePath, '# Prompt Enhancement Log\n\n', {
        encoding: 'utf-8',
      });

      console.log(`[EnhancementLogger] Log file initialized: ${this.logFilePath}`);
    } catch (error) {
      console.error(`[EnhancementLogger] Failed to initialize log file:`, error);
      this.isEnabled = false;
    }
  }

  log(entry: EnhancementLogEntry): void {
    if (!this.isEnabled || !this.logFilePath) {
      return;
    }

    try {
      const newLogEntry = this.formatLogEntry(entry);

      // Read existing content
      const existingContent = existsSync(this.logFilePath)
        ? readFileSync(this.logFilePath, 'utf-8')
        : '# Prompt Enhancement Log\n\n';

      // Insert new entry AFTER header but BEFORE old entries
      const headerEnd = existingContent.indexOf('\n\n') + 2;
      const header = existingContent.slice(0, headerEnd);
      const oldEntries = existingContent.slice(headerEnd);

      writeFileSync(this.logFilePath, header + newLogEntry + oldEntries, 'utf-8');
    } catch (error) {
      console.error(`[EnhancementLogger] Failed to write log entry:`, error);
    }
  }

  private formatLogEntry(entry: EnhancementLogEntry): string {
    const {
      timestamp,
      orgId,
      projectId,
      originalPrompt,
      enhancedPrompt,
      meta,
      template,
      detectedLanguage,
      enhancements,
      model,
    } = entry;

    // Format date from ISO timestamp
    const date = new Date(timestamp);
    const formattedDate = date.toISOString().replace('T', ' ').slice(0, 19);

    let logText = `## ${formattedDate}\n`;
    logText += `${orgId}/${projectId}\n\n`;
    logText += `**Original Prompt:** ${originalPrompt}\n\n`;
    logText += `**Enhanced Prompt:** ${enhancedPrompt}\n\n`;

    // Add tags if present
    if (meta?.tags && meta.tags.length > 0) {
      logText += `**Tags:** ${meta.tags.join(', ')}\n\n`;
    }

    logText += `**Template:** ${template}\n`;
    if (detectedLanguage) {
      logText += `**Language:** ${detectedLanguage}\n`;
    }
    if (enhancements.length > 0) {
      logText += `**Enhancements:** ${enhancements.join(', ')}\n`;
    }
    logText += `**Model:** ${model}\n\n`;
    logText += `---\n\n`;

    return logText;
  }
}
