import fs from 'fs';
import path from 'path';
import { parentPort } from 'worker_threads';

function isVideoFile(file: string): boolean {
  const ext = path.extname(file).toLowerCase();
  const videoExts = ['.avi', '.mkv', '.mov', '.mp4', '.m4v'];
  return videoExts.includes(ext);
}

function isValidVideoFile(file: string): boolean {
  try {
    // Check if file exists and is readable
    if (!fs.existsSync(file)) {
      return false;
    }

    const stats = fs.statSync(file);
    if (stats.size === 0) {
      return false;
    }

    // Read first few bytes to check for video file signatures
    const buffer = Buffer.alloc(12);
    const fd = fs.openSync(file, 'r');
    try {
      fs.readSync(fd, buffer, 0, 12, 0);
    } finally {
      fs.closeSync(fd);
    }

    // Check for common video file signatures
    const signature = buffer.toString('hex');

    // MP4 signature (ftyp box)
    if (signature.includes('66747970')) {
      return true;
    }

    // MKV/WebM signature (EBML)
    if (signature.startsWith('1a45dfa3')) {
      return true;
    }

    // AVI signature (RIFF)
    if (
      signature.startsWith('52494646') &&
      buffer.toString('ascii', 8, 12) === 'AVI '
    ) {
      return true;
    }

    // MOV signature (ftyp)
    if (signature.includes('66747971') || signature.includes('66747970')) {
      return true;
    }

    // For other formats, just check if file is large enough to be a video (> 1MB)
    // This is a basic heuristic since not all video formats have easily detectable headers
    return stats.size > 1024 * 1024;
  } catch (error) {
    console.warn(`Error validating video file ${file}: ${error}`);
    return false;
  }
}

parentPort?.on('message', (message) => {
  if (message.type === 'validate_file') {
    const { file } = message;
    const isVideo = isVideoFile(file);
    const isValid = isVideo && isValidVideoFile(file);
    parentPort?.postMessage({
      type: 'validation_result',
      file,
      isVideo,
      isValid,
    });
  }
});
