import { Request, Response } from 'express';
import { PromptEnhancementService } from '../services/promptEnhancement';
import { EnhancedGenerateImageRequest } from '../types/api';

let promptEnhancementService: PromptEnhancementService | null = null;

interface RequestWithEnhancement extends Request {
  body: EnhancedGenerateImageRequest;
  enhancedPrompt?: string;
  originalPrompt?: string;
  enhancementMetadata?: {
    detectedLanguage?: string;
    appliedTemplate?: string;
    enhancements: string[];
  };
}

export const autoEnhancePrompt = async (
  req: RequestWithEnhancement,
  _res: Response,
  next: Function,
): Promise<void> => {
  const timestamp = new Date().toISOString();
  const requestId = req.requestId;
  const { prompt, autoEnhance, enhancementOptions } = req.body;

  // Default autoEnhance to true if not explicitly set to false
  const shouldEnhance = autoEnhance !== false;

  if (!shouldEnhance) {
    console.log(`[${timestamp}] [${requestId}] Auto-enhancement explicitly disabled, skipping`);
    return next();
  }

  console.log(`[${timestamp}] [${requestId}] Auto-enhancement enabled, processing prompt`);

  try {
    if (!promptEnhancementService) {
      const apiKey = process.env['GEMINI_API_KEY'];
      if (!apiKey) {
        console.error(
          `[${timestamp}] [${requestId}] Cannot initialize prompt enhancement: Missing API key`,
        );
        return next();
      }
      promptEnhancementService = new PromptEnhancementService(apiKey);
    }

    // Extract orgId and projectId from validated API key
    const orgId = req.apiKey?.organizationSlug || 'unknown';
    const projectId = req.apiKey?.projectSlug || 'unknown';

    const result = await promptEnhancementService.enhancePrompt(
      prompt,
      {
        ...enhancementOptions,
        ...(req.body.meta?.tags && { tags: req.body.meta.tags }),
      },
      {
        orgId,
        projectId,
        ...(req.body.meta && { meta: req.body.meta }),
      },
    );

    if (result.success && result.enhancedPrompt) {
      console.log(`[${timestamp}] [${requestId}] Prompt enhanced successfully`);
      console.log(`[${timestamp}] [${requestId}] Original: "${prompt.substring(0, 50)}..."`);
      console.log(
        `[${timestamp}] [${requestId}] Enhanced: "${result.enhancedPrompt.substring(0, 50)}..."`,
      );

      req.originalPrompt = prompt;
      req.enhancedPrompt = result.enhancedPrompt;
      req.enhancementMetadata = {
        ...(result.detectedLanguage && {
          detectedLanguage: result.detectedLanguage,
        }),
        ...(result.appliedTemplate && {
          appliedTemplate: result.appliedTemplate,
        }),
        enhancements: result.metadata?.enhancements || [],
      };
    } else {
      console.warn(`[${timestamp}] [${requestId}] Prompt enhancement failed: ${result.error}`);
      console.log(`[${timestamp}] [${requestId}] Proceeding with original prompt`);
    }
  } catch (error) {
    console.error(`[${timestamp}] [${requestId}] Error during auto-enhancement:`, error);
    console.log(`[${timestamp}] [${requestId}] Proceeding with original prompt`);
  }

  next();
};

export const logEnhancementResult = (
  req: RequestWithEnhancement,
  _res: Response,
  next: Function,
): void => {
  if (req.enhancedPrompt && req.enhancementMetadata) {
    const timestamp = new Date().toISOString();
    const requestId = req.requestId;

    console.log(`[${timestamp}] [${requestId}] Enhancement applied:`, {
      detectedLanguage: req.enhancementMetadata.detectedLanguage,
      appliedTemplate: req.enhancementMetadata.appliedTemplate,
      enhancementsCount: req.enhancementMetadata.enhancements.length,
      enhancements: req.enhancementMetadata.enhancements,
    });
  }

  next();
};
