#!/usr/bin/env tsx
/**
 * Comprehensive test for embed components
 */

import { readFileSync, existsSync } from 'fs';
import { join } from 'path';

const componentsDir = join(process.cwd(), 'src', 'components');

interface TestResult {
  name: string;
  passed: boolean;
  details: string;
}

const results: TestResult[] = [];

// Test 1: Check component files exist
function testComponentFiles(): TestResult {
  const files = [
    'YouTubeEmbed.astro',
    'TwitterEmbed.astro',
    'GenericEmbed.astro'
  ];
  
  const missing = files.filter(file => !existsSync(join(componentsDir, file)));
  
  if (missing.length === 0) {
    return {
      name: 'Component Files Exist',
      passed: true,
      details: 'All embed components found'
    };
  }
  
  return {
    name: 'Component Files Exist',
    passed: false,
    details: `Missing: ${missing.join(', ')}`
  };
}

// Test 2: Check component structure
function testComponentStructure(): TestResult {
  const youtubeContent = readFileSync(join(componentsDir, 'YouTubeEmbed.astro'), 'utf-8');
  const twitterContent = readFileSync(join(componentsDir, 'TwitterEmbed.astro'), 'utf-8');
  const genericContent = readFileSync(join(componentsDir, 'GenericEmbed.astro'), 'utf-8');
  
  const issues: string[] = [];
  
  // Check YouTube structure
  if (!youtubeContent.includes('interface Props')) issues.push('YouTube: Missing Props interface');
  if (!youtubeContent.includes('embedUrl')) issues.push('YouTube: Missing embed URL');
  if (!youtubeContent.includes('<iframe')) issues.push('YouTube: Missing iframe');
  
  // Check Twitter structure
  if (!twitterContent.includes('oEmbed')) issues.push('Twitter: Missing oEmbed logic');
  if (!twitterContent.includes('fallbackHtml')) issues.push('Twitter: Missing fallback');
  if (!twitterContent.includes('set:html')) issues.push('Twitter: Missing HTML injection');
  
  // Check Generic structure
  if (!genericContent.includes('oEmbedEndpoints')) issues.push('Generic: Missing oEmbed endpoints');
  if (!genericContent.includes('provider')) issues.push('Generic: Missing provider detection');
  
  if (issues.length === 0) {
    return {
      name: 'Component Structure',
      passed: true,
      details: 'All components have correct structure'
    };
  }
  
  return {
    name: 'Component Structure',
    passed: false,
    details: issues.join('; ')
  };
}

// Test 3: Check for common issues
function testCommonIssues(): TestResult {
  const youtubeContent = readFileSync(join(componentsDir, 'YouTubeEmbed.astro'), 'utf-8');
  const twitterContent = readFileSync(join(componentsDir, 'TwitterEmbed.astro'), 'utf-8');
  
  const issues: string[] = [];
  
  // Check for problematic Intersection Observer
  if (youtubeContent.includes('IntersectionObserver')) {
    issues.push('YouTube: Still using IntersectionObserver (may cause blinking)');
  }
  
  // Check for timeout issues
  if (twitterContent.includes('timeout:')) {
    issues.push('Twitter: Has timeout property (not supported in fetch)');
  }
  
  // Check for proper error handling
  if (!twitterContent.includes('try') || !twitterContent.includes('catch')) {
    issues.push('Twitter: Missing try/catch error handling');
  }
  
  if (issues.length === 0) {
    return {
      name: 'Common Issues Check',
      passed: true,
      details: 'No common issues detected'
    };
  }
  
  return {
    name: 'Common Issues Check',
    passed: false,
    details: issues.join('; ')
  };
}

// Test 4: Check demo post exists
function testDemoPost(): TestResult {
  const demoPath = join(process.cwd(), 'src', 'pages', 'blog', 'embed-demo.astro');
  
  if (existsSync(demoPath)) {
    const content = readFileSync(demoPath, 'utf-8');
    
    const hasYouTube = content.includes('YouTubeEmbed');
    const hasTwitter = content.includes('TwitterEmbed');
    const hasGeneric = content.includes('GenericEmbed');
    
    if (hasYouTube && hasTwitter && hasGeneric) {
      return {
        name: 'Demo Post',
        passed: true,
        details: 'Demo post exists with all components'
      };
    }
    
    return {
      name: 'Demo Post',
      passed: false,
      details: `Missing components: ${!hasYouTube ? 'YouTube' : ''} ${!hasTwitter ? 'Twitter' : ''} ${!hasGeneric ? 'Generic' : ''}`
    };
  }
  
  return {
    name: 'Demo Post',
    passed: false,
    details: 'Demo post file not found'
  };
}

// Test 5: Check blogPosts array
function testBlogPostsArray(): TestResult {
  const blogPostsPath = join(process.cwd(), 'src', 'data', 'blogPosts.ts');
  
  if (!existsSync(blogPostsPath)) {
    return {
      name: 'Blog Posts Array',
      passed: false,
      details: 'blogPosts.ts not found'
    };
  }
  
  const content = readFileSync(blogPostsPath, 'utf-8');
  
  if (content.includes('embed-demo')) {
    return {
      name: 'Blog Posts Array',
      passed: true,
      details: 'embed-demo found in blogPosts array'
    };
  }
  
  return {
    name: 'Blog Posts Array',
    passed: false,
    details: 'embed-demo not found in blogPosts array'
  };
}

// Run all tests
console.log('🔍 Running Comprehensive Embed Component Tests...\n');

results.push(testComponentFiles());
results.push(testComponentStructure());
results.push(testCommonIssues());
results.push(testDemoPost());
results.push(testBlogPostsArray());

// Display results
let allPassed = true;
results.forEach(result => {
  const icon = result.passed ? '✅' : '❌';
  console.log(`${icon} ${result.name}`);
  console.log(`   ${result.details}`);
  if (!result.passed) allPassed = false;
});

console.log('\n' + '='.repeat(60));

if (allPassed) {
  console.log('🎉 All tests passed! Components should work correctly.');
  console.log('\nNext steps:');
  console.log('1. Visit http://localhost:4321/blog/embed-demo');
  console.log('2. Check browser console for any errors');
  console.log('3. If Twitter fails, it needs internet during build');
} else {
  console.log('❌ Some tests failed. Check the details above.');
  console.log('\nCommon fixes:');
  console.log('- Restart dev server: npm run dev');
  console.log('- Check internet connection for Twitter oEmbed');
  console.log('- Verify video IDs and tweet IDs are valid');
}

process.exit(allPassed ? 0 : 1);