<?php
// ============================================================
//  M3U8 → MP4 Worker (CLI orqali ishga tushiriladi)
//  Ishlatilishi: php worker.php <chat_id> <m3u8_url> [wait_msg_id]
// ============================================================

// Vaqt chegarasi yo'q (katta videolar uchun)
set_time_limit(0);

// CLI dan ishga tushirilganligini tekshirish
if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    exit('Only CLI');
}

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/helpers.php';

// ── Argumentlarni o'qish ──────────────────────────────────────
$chatId    = (string)($argv[1] ?? '');
$m3u8Url   = (string)($argv[2] ?? '');
$waitMsgId = (int)($argv[3] ?? 0);

if (!$chatId || !$m3u8Url) {
    logMessage("Worker: missing arguments. chat_id={$chatId}, url={$m3u8Url}");
    exit(1);
}

logMessage("Worker START | chat_id={$chatId} | url={$m3u8Url}");

// ── 1. Chiqish fayl nomini belgilash ─────────────────────────
$filename   = generateFilename($chatId);
$outputPath = DOWNLOAD_DIR . DIRECTORY_SEPARATOR . $filename;

// ── 2. FFmpeg buyrug'ini qurish ───────────────────────────────
//     -y          → mavjud faylni ustiga yozish
//     -loglevel   → faqat xatolarni ko'rsatish
//     -i          → kirish URL (m3u8)
//     scale       → 1920xauto (nisbat saqlanadi, -2 juft son ta'minlaydi)
//     -c:v        → libx264 (H.264 kodek)
//     -preset     → fast (tezlik va sifat muvozanati)
//     -crf        → 23 (0-51, past = sifatli, 23 = o'rtacha)
//     -c:a        → aac audio kodek
//     -b:a        → 192k audio bitrate
//     -movflags   → faststart (progressiv o'ynash)
//     -threads    → 4 yadro ishlatish

$ffmpeg   = FFMPEG_PATH;
$videoOpt = FFMPEG_VIDEO_OPTS;
$audioOpt = FFMPEG_AUDIO_OPTS;
$extraOpt = FFMPEG_EXTRA_OPTS;

$cmd = "\"{$ffmpeg}\" -y -loglevel error "
     . "-i \"{$m3u8Url}\" "
     . "{$videoOpt} "
     . "{$audioOpt} "
     . "{$extraOpt} "
     . "\"{$outputPath}\" 2>&1";

logMessage("FFmpeg CMD: {$cmd}");

// ── 3. FFmpeg ni ishga tushirish ──────────────────────────────
$ffmpegOutput = [];
$exitCode     = 0;
$startTime    = time();

exec($cmd, $ffmpegOutput, $exitCode);

$elapsed = time() - $startTime;
logMessage("FFmpeg finished | exit_code={$exitCode} | elapsed={$elapsed}s");

if ($ffmpegOutput) {
    logMessage("FFmpeg output: " . implode(' | ', array_slice($ffmpegOutput, 0, 5)));
}

// ── 4. Xato tekshirish ────────────────────────────────────────
if ($exitCode !== 0 || !file_exists($outputPath) || filesize($outputPath) < 1024) {
    $errorDetail = implode("\n", array_slice($ffmpegOutput, 0, 3));
    $errMsg = "❌ <b>Konvertatsiya xatosi!</b>\n\n"
        . "URL erishib bo'lmaydi yoki video formati qo'llab-quvvatlanmaydi.\n\n"
        . ($errorDetail ? "<code>" . htmlspecialchars(substr($errorDetail, 0, 200)) . "</code>" : '');

    if ($waitMsgId) {
        editMessage($chatId, $waitMsgId, $errMsg);
    } else {
        sendMessage($chatId, $errMsg);
    }

    if (file_exists($outputPath)) {
        unlink($outputPath);
    }

    logMessage("Worker FAILED | chat_id={$chatId}");
    exit(1);
}

// ── 5. Fayl hajmini aniqlash ──────────────────────────────────
$fileSize    = filesize($outputPath);
$fileSizeFmt = formatBytes($fileSize);

logMessage("File ready | size={$fileSizeFmt} | path={$outputPath}");

// ── 6. Caption matni ──────────────────────────────────────────
$caption = "🎬 <b>1080p MP4 Video</b>\n"
    . "📦 Hajm: <b>{$fileSizeFmt}</b>\n"
    . "⏱ Konvertatsiya vaqti: <b>{$elapsed} soniya</b>\n"
    . "🤖 <i>M3U8 → MP4 Bot</i>";

// ── 7. 50 MB dan kichik → Bot API sendVideo ───────────────────
if ($fileSize <= MAX_SEND_SIZE) {

    logMessage("Sending as video (Bot API)...");

    $sendingMsg = "✅ <b>Tayyor!</b> Bot orqali yuborilmoqda...\n\n"
        . "📦 Hajm: <b>{$fileSizeFmt}</b>\n"
        . "⏱ FFmpeg vaqti: <b>{$elapsed} soniya</b>";

    if ($waitMsgId) {
        editMessage($chatId, $waitMsgId, $sendingMsg);
    } else {
        sendMessage($chatId, $sendingMsg);
    }

    $result = sendVideo($chatId, $outputPath, $caption);

    if (!empty($result['ok'])) {
        logMessage("Worker SUCCESS (Bot API) | chat_id={$chatId} | size={$fileSizeFmt}");
        if ($waitMsgId) {
            telegramRequest('deleteMessage', [
                'chat_id'    => $chatId,
                'message_id' => $waitMsgId,
            ]);
        }
    } else {
        $apiErr = $result['description'] ?? 'Noma\'lum xato';
        logMessage("Send FAILED | chat_id={$chatId} | error={$apiErr}");
        sendMessage($chatId,
            "❌ <b>Yuborishda xato:</b>\n<code>" . htmlspecialchars($apiErr) . "</code>"
        );
    }

    // Faylni o'chirish
    if (file_exists($outputPath)) {
        unlink($outputPath);
        logMessage("Temp file deleted: {$outputPath}");
    }

// ── 8. 50 MB dan katta → MadelineProto UserBot ───────────────
} else {

    logMessage("Large file ({$fileSizeFmt}). Switching to MadelineProto uploader...");

    if ($waitMsgId) {
        editMessage($chatId, $waitMsgId,
            "📦 <b>Katta fayl aniqlandi: {$fileSizeFmt}</b>\n\n"
            . "🤖 UserBot (MadelineProto) orqali yuklanmoqda...\n"
            . "⏳ Iltimos, kuting. Bu bir necha daqiqa vaqt olishi mumkin..."
        );
    }

    $phpPath      = PHP_PATH;
    $uploaderPath = __DIR__ . DIRECTORY_SEPARATOR . 'madeline_uploader.php';
    $escapedFile  = escapeshellarg($outputPath);
    $escapedCid   = escapeshellarg((string)$chatId);
    $escapedCap   = escapeshellarg($caption);
    $escapedMid   = escapeshellarg((string)$waitMsgId);

    // Sinxron — madeline_uploader tugaguncha kutamiz
    // (Fayl u yerda o'chiriladi)
    $cmd2 = "\"{$phpPath}\" \"{$uploaderPath}\" {$escapedCid} {$escapedFile} {$escapedCap} {$escapedMid}";
    logMessage("MadelineProto CMD: {$cmd2}");

    exec($cmd2, $mOut, $mExit);

    if ($mExit !== 0) {
        logMessage("MadelineProto uploader exit_code={$mExit} | output=" . implode(' | ', array_slice($mOut, 0, 3)));
    } else {
        logMessage("MadelineProto uploader SUCCESS | chat_id={$chatId}");
    }
    // Fayl madeline_uploader.php ichida o'chirilgan bo'lishi kerak
    // Tekshirib qo'yamiz:
    if (file_exists($outputPath)) {
        unlink($outputPath);
        logMessage("Temp file cleanup: {$outputPath}");
    }
}
