/**
 * Image Canon Audit - LocalLendables
 * Audits and reports on image compliance with the Image Canon standards
 */

import { readdirSync, statSync } from 'fs';
import path from 'path';

export class ImageCanonAudit {
  private readonly imagesDir = path.join(process.cwd(), 'public', 'lendable_items');
  
  async auditImageCompliance(): Promise<{
    totalImages: number;
    hasThumbnails: number;
    missingThumbnails: string[];
    oversizedImages: string[];
    compressionNeeded: string[];
    summary: string;
  }> {
    const results = {
      totalImages: 0,
      hasThumbnails: 0,
      missingThumbnails: [] as string[],
      oversizedImages: [] as string[],
      compressionNeeded: [] as string[],
      summary: ''
    };
    
    try {
      const files = readdirSync(this.imagesDir);
      const imageFiles = files.filter(file => 
        /\.(jpg|jpeg|png|gif|webp)$/i.test(file) && 
        !file.includes('_thumb')
      );
      
      results.totalImages = imageFiles.length;
      
      for (const imageFile of imageFiles) {
        const imagePath = path.join(this.imagesDir, imageFile);
        const stats = statSync(imagePath);
        
        // Check for corresponding thumbnail
        const ext = path.extname(imageFile);
        const nameWithoutExt = path.basename(imageFile, ext);
        const thumbnailName = `${nameWithoutExt}_thumb${ext}`;
        const thumbnailExists = files.includes(thumbnailName);
        
        if (thumbnailExists) {
          results.hasThumbnails++;
        } else {
          results.missingThumbnails.push(imageFile);
        }
        
        // Check for oversized images (>1MB suggests need for optimization)
        if (stats.size > 1024 * 1024) {
          results.oversizedImages.push(`${imageFile} (${(stats.size / 1024 / 1024).toFixed(1)}MB)`);
        }
        
        // Check for images that need compression (>500KB for main images)
        if (stats.size > 500 * 1024) {
          results.compressionNeeded.push(`${imageFile} (${(stats.size / 1024).toFixed(0)}KB)`);
        }
      }
      
      // Generate summary
      const thumbnailPercentage = ((results.hasThumbnails / results.totalImages) * 100).toFixed(1);
      results.summary = `
Image Canon Compliance Report:
- Total images: ${results.totalImages}
- Images with thumbnails: ${results.hasThumbnails} (${thumbnailPercentage}%)
- Missing thumbnails: ${results.missingThumbnails.length}
- Oversized images: ${results.oversizedImages.length}
- Images needing compression: ${results.compressionNeeded.length}

Compliance level: ${thumbnailPercentage}% thumbnail coverage
Optimization needed: ${results.compressionNeeded.length} images
      `.trim();
      
    } catch (error) {
      console.error('Error during image audit:', error);
    }
    
    return results;
  }
  
  async printAuditReport(): Promise<void> {
    const audit = await this.auditImageCompliance();
    console.log('\n=== LocalLendables Image Canon Audit ===');
    console.log(audit.summary);
    
    if (audit.missingThumbnails.length > 0) {
      console.log('\nMissing thumbnails:');
      audit.missingThumbnails.slice(0, 10).forEach(file => console.log(`  - ${file}`));
      if (audit.missingThumbnails.length > 10) {
        console.log(`  ... and ${audit.missingThumbnails.length - 10} more`);
      }
    }
    
    if (audit.oversizedImages.length > 0) {
      console.log('\nOversized images (>1MB):');
      audit.oversizedImages.slice(0, 5).forEach(file => console.log(`  - ${file}`));
      if (audit.oversizedImages.length > 5) {
        console.log(`  ... and ${audit.oversizedImages.length - 5} more`);
      }
    }
    
    console.log('\n=== End Audit Report ===\n');
  }
}

export const imageCanonAudit = new ImageCanonAudit();