// tests/api/08-auto-enhance.ts
// Auto-Enhance Feature Tests

import { api, log, runTest, waitForGeneration, testContext, exitWithTestResults } from './utils';
import { endpoints } from './config';

async function main() {
  log.section('AUTO-ENHANCE TESTS');

  // Test 1: Generation without autoEnhance parameter (should default to true)
  await runTest('Generate without autoEnhance param → should enhance', async () => {
    const result = await api(endpoints.generations, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        prompt: 'a simple test image',
        aspectRatio: '1:1',
        // No autoEnhance parameter - should default to true
      }),
    });

    if (!result.data.data || !result.data.data.id) {
      throw new Error('No generation returned');
    }

    const generation = await waitForGeneration(result.data.data.id);

    if (generation.status !== 'success') {
      throw new Error(`Generation failed: ${generation.errorMessage}`);
    }

    // Verify enhancement happened
    if (!generation.originalPrompt) {
      throw new Error('originalPrompt should be populated when enhanced');
    }

    if (!generation.autoEnhance) {
      throw new Error('autoEnhance should be true');
    }

    if (generation.prompt === generation.originalPrompt) {
      throw new Error('prompt and originalPrompt should be different (enhancement happened)');
    }

    log.detail('Original prompt', generation.originalPrompt);
    log.detail('Enhanced prompt', generation.prompt);
    log.detail('autoEnhance', generation.autoEnhance);
    log.detail('Enhancement confirmed', '✓');

    testContext.enhancedGenId = generation.id;
  });

  // Test 2: Generation with autoEnhance: false
  await runTest('Generate with autoEnhance: false → should NOT enhance', async () => {
    const result = await api(endpoints.generations, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        prompt: 'another test image',
        aspectRatio: '1:1',
        autoEnhance: false,
      }),
    });

    if (!result.data.data || !result.data.data.id) {
      throw new Error('No generation returned');
    }

    const generation = await waitForGeneration(result.data.data.id);

    if (generation.status !== 'success') {
      throw new Error(`Generation failed: ${generation.errorMessage}`);
    }

    // Verify NO enhancement happened
    if (!generation.originalPrompt) {
      throw new Error('originalPrompt should be populated with original input');
    }

    if (generation.autoEnhance) {
      throw new Error('autoEnhance should be false');
    }

    if (generation.prompt !== generation.originalPrompt) {
      throw new Error('prompt and originalPrompt should be the SAME when NOT enhanced');
    }

    if (generation.prompt !== 'another test image') {
      throw new Error('both prompts should match original input (no enhancement)');
    }

    log.detail('Prompt', generation.prompt);
    log.detail('originalPrompt', generation.originalPrompt);
    log.detail('autoEnhance', generation.autoEnhance);
    log.detail('Prompts match (no enhancement)', '✓');

    testContext.notEnhancedGenId = generation.id;
  });

  // Test 3: Generation with explicit autoEnhance: true
  await runTest('Generate with autoEnhance: true → should enhance', async () => {
    const result = await api(endpoints.generations, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        prompt: 'third test image',
        aspectRatio: '1:1',
        autoEnhance: true,
      }),
    });

    if (!result.data.data || !result.data.data.id) {
      throw new Error('No generation returned');
    }

    const generation = await waitForGeneration(result.data.data.id);

    if (generation.status !== 'success') {
      throw new Error(`Generation failed: ${generation.errorMessage}`);
    }

    // Verify enhancement happened
    if (!generation.originalPrompt) {
      throw new Error('originalPrompt should be populated');
    }

    if (!generation.autoEnhance) {
      throw new Error('autoEnhance should be true');
    }

    if (generation.originalPrompt !== 'third test image') {
      throw new Error('originalPrompt should match input');
    }

    if (generation.prompt === generation.originalPrompt) {
      throw new Error('prompt should be enhanced (different from original)');
    }

    log.detail('Original prompt', generation.originalPrompt);
    log.detail('Enhanced prompt', generation.prompt);
    log.detail('autoEnhance', generation.autoEnhance);
    log.detail('Enhancement confirmed', '✓');
  });

  // Test 4: Verify enhanced prompt is actually different and longer
  await runTest('Verify enhancement quality', async () => {
    const result = await api(`${endpoints.generations}/${testContext.enhancedGenId}`);
    const generation = result.data.data;

    const originalLength = generation.originalPrompt?.length || 0;
    const enhancedLength = generation.prompt?.length || 0;

    if (enhancedLength <= originalLength) {
      log.warning('Enhanced prompt not longer than original (might not be truly enhanced)');
    } else {
      log.detail('Original length', originalLength);
      log.detail('Enhanced length', enhancedLength);
      log.detail('Increase', `+${enhancedLength - originalLength} chars`);
    }

    // Verify the enhanced prompt contains more descriptive language
    const hasPhotorealistic = generation.prompt.toLowerCase().includes('photorealistic') ||
                             generation.prompt.toLowerCase().includes('realistic') ||
                             generation.prompt.toLowerCase().includes('detailed');

    if (hasPhotorealistic) {
      log.detail('Enhancement adds descriptive terms', '✓');
    }
  });

  // Test 5: Verify both enhanced and non-enhanced are in listings
  await runTest('List generations - verify autoEnhance field', async () => {
    const result = await api(endpoints.generations);

    if (!result.data.data || !Array.isArray(result.data.data)) {
      throw new Error('No generations array returned');
    }

    const enhancedGens = result.data.data.filter((g: any) => g.autoEnhance === true);
    const notEnhancedGens = result.data.data.filter((g: any) => g.autoEnhance === false);

    log.detail('Total generations', result.data.data.length);
    log.detail('Enhanced', enhancedGens.length);
    log.detail('Not enhanced', notEnhancedGens.length);

    if (enhancedGens.length === 0) {
      throw new Error('Should have at least one enhanced generation');
    }

    if (notEnhancedGens.length === 0) {
      throw new Error('Should have at least one non-enhanced generation');
    }
  });

  // Test 6: Verify response structure
  await runTest('Verify response includes all enhancement fields', async () => {
    const result = await api(`${endpoints.generations}/${testContext.enhancedGenId}`);
    const generation = result.data.data;

    // Required fields
    if (typeof generation.prompt !== 'string') {
      throw new Error('prompt should be string');
    }

    if (typeof generation.autoEnhance !== 'boolean') {
      throw new Error('autoEnhance should be boolean');
    }

    // originalPrompt can be null or string
    if (generation.originalPrompt !== null && typeof generation.originalPrompt !== 'string') {
      throw new Error('originalPrompt should be null or string');
    }

    log.detail('Response structure', 'valid ✓');
    log.detail('prompt type', typeof generation.prompt);
    log.detail('originalPrompt type', typeof generation.originalPrompt || 'null');
    log.detail('autoEnhance type', typeof generation.autoEnhance);
  });

  log.section('AUTO-ENHANCE TESTS COMPLETED');
}

main()
  .then(() => exitWithTestResults())
  .catch((error) => {
    console.error('Unexpected error:', error);
    process.exit(1);
  });
