#!/usr/bin/env php
<?php
/**
 * اختبار معالجة فيديو واحد
 * 
 * الاستخدام:
 * php test_single_video.php <post_id>
 * 
 * مثال:
 * php test_single_video.php 2020965931523158098
 */

if ($argc < 2) {
    echo "Usage: php test_single_video.php <post_id>\n";
    echo "Example: php test_single_video.php 2020965931523158098\n";
    exit(1);
}

$postId = $argv[1];

set_time_limit(0);
ini_set('max_execution_time', 0);

require_once dirname(__DIR__) . '/inc/con.php';

// الإعدادات
$media_dir = __DIR__ . '/upload_media/';
$ffmpeg_path = '/opt/homebrew/bin/ffmpeg';

// التحقق من FFmpeg
echo "Checking FFmpeg...\n";
exec("$ffmpeg_path -version 2>&1", $output, $return_var);
if ($return_var !== 0) {
    // محاولة إيجاد FFmpeg في مسارات أخرى
    $possible_paths = [
        '/usr/bin/ffmpeg',
        '/usr/local/bin/ffmpeg',
        '/opt/homebrew/bin/ffmpeg'
    ];

    $found = false;
    foreach ($possible_paths as $path) {
        if (file_exists($path)) {
            $ffmpeg_path = $path;
            $found = true;
            echo "Found FFmpeg at: $path\n";
            break;
        }
    }

    if (!$found) {
        echo "ERROR: FFmpeg not found. Please install it first:\n";
        echo "  macOS: brew install ffmpeg\n";
        echo "  Linux: sudo apt install ffmpeg\n";
        exit(1);
    }
} else {
    echo "FFmpeg OK: " . $output[0] . "\n";
}

// البحث عن الفيديو
echo "\nSearching for video with post_id: $postId\n";

try {
    $sql = "SELECT id, post_id, video_url, video_processing 
            FROM social_media_content 
            WHERE post_id = ?";
    $stmt = $db->prepare($sql);
    $stmt->execute([$postId]);
    $video = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$video) {
        echo "ERROR: Video not found with post_id: $postId\n";
        exit(1);
    }

    if (empty($video['video_url'])) {
        echo "ERROR: No video file associated with this post\n";
        exit(1);
    }

    echo "Found video:\n";
    echo "  ID: " . $video['id'] . "\n";
    echo "  Post ID: " . $video['post_id'] . "\n";
    echo "  Video: " . $video['video_url'] . "\n";
    echo "  Processing Status: " . $video['video_processing'] . "\n\n";

    $inputFile = $media_dir . $video['video_url'];

    if (!file_exists($inputFile)) {
        echo "ERROR: Video file not found: $inputFile\n";
        exit(1);
    }

    $fileSize = filesize($inputFile);
    echo "Video file size: " . number_format($fileSize / 1024 / 1024, 2) . " MB\n\n";

    // إنشاء مجلد الإخراج
    $outputDir = $media_dir . $postId . '_hls/';
    echo "Output directory: $outputDir\n";

    if (is_dir($outputDir)) {
        echo "WARNING: Output directory already exists. It will be recreated.\n";
        // حذف المجلد القديم
        exec("rm -rf " . escapeshellarg($outputDir));
    }

    mkdir($outputDir, 0755, true);

    // معالجة جودة واحدة للاختبار (480p)
    echo "\n=== Processing 480p (test) ===\n";

    $qualityDir = $outputDir . '480p/';
    mkdir($qualityDir, 0755, true);

    $playlistFile = $qualityDir . 'playlist.m3u8';
    $segmentPattern = $qualityDir . 'segment_%03d.ts';

    $cmd = sprintf(
        '%s -i %s ' .
        '-vf scale=854:480 ' .
        '-c:v libx264 -b:v 1400k -preset medium ' .
        '-c:a aac -b:a 128k ' .
        '-hls_time 10 ' .
        '-hls_playlist_type vod ' .
        '-hls_segment_filename %s ' .
        '%s 2>&1',
        escapeshellarg($ffmpeg_path),
        escapeshellarg($inputFile),
        escapeshellarg($segmentPattern),
        escapeshellarg($playlistFile)
    );

    echo "Command: $cmd\n\n";
    echo "Processing... (this may take a while)\n";

    $startTime = microtime(true);
    exec($cmd, $output, $return_var);
    $endTime = microtime(true);

    $duration = round($endTime - $startTime, 2);

    if ($return_var !== 0) {
        echo "\nERROR: Processing failed\n";
        echo "Output:\n" . implode("\n", array_slice($output, -20)) . "\n";
        exit(1);
    }

    echo "\nSUCCESS! Processing completed in {$duration}s\n";

    // التحقق من الملفات
    if (file_exists($playlistFile)) {
        echo "✓ Playlist created: $playlistFile\n";

        $segments = glob($qualityDir . 'segment_*.ts');
        echo "✓ Segments created: " . count($segments) . " files\n";

        // حساب حجم الملفات
        $totalSize = 0;
        foreach ($segments as $segment) {
            $totalSize += filesize($segment);
        }
        $totalSize += filesize($playlistFile);

        echo "✓ Total size: " . number_format($totalSize / 1024 / 1024, 2) . " MB\n";
        echo "✓ Compression: " . round(($totalSize / $fileSize) * 100, 1) . "%\n";

        // عرض محتوى playlist
        echo "\nPlaylist content:\n";
        echo str_repeat("-", 50) . "\n";
        echo file_get_contents($playlistFile);
        echo str_repeat("-", 50) . "\n";

        echo "\n✅ Test completed successfully!\n";
        echo "\nYou can now test playback with:\n";
        echo "  Video URL: upload_media/{$postId}_hls/480p/playlist.m3u8\n";

    } else {
        echo "ERROR: Playlist file not created\n";
        exit(1);
    }

} catch (Exception $e) {
    echo "ERROR: " . $e->getMessage() . "\n";
    exit(1);
}
