<?php
// ============================================
// بث مباشر من GitHub - النسخة النهائية
// ============================================

// إعدادات
$user = "mgmgmgmgyyyy2-boop";
$repo = "blue";
$token = "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";
$max_segments = 10;

// جلب الملفات
$url = "https://api.github.com/repos/$user/$repo/contents/";
$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERAGENT => "HLS-Proxy/1.0",
    CURLOPT_HTTPHEADER => [
        "Authorization: token $token",
        "Accept: application/vnd.github.v3+json"
    ],
    CURLOPT_TIMEOUT => 10,
    CURLOPT_FOLLOWLOCATION => true
]);

$res = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);

// معالجة الأخطاء
if ($http_code !== 200 || empty($res)) {
    http_response_code(500);
    header("Content-Type: application/json");
    echo json_encode([
        "error" => "GitHub API failed",
        "code" => $http_code,
        "message" => $error
    ]);
    exit;
}

$files = json_decode($res, true);

if (!is_array($files) || empty($files)) {
    http_response_code(500);
    echo json_encode(["error" => "Invalid response"]);
    exit;
}

// استخراج ملفات TS
$segments = [];
foreach ($files as $file) {
    if (isset($file['name']) && str_ends_with($file['name'], '.ts')) {
        // استخراج الرقم من اسم الملف
        preg_match('/ts_(\d+)\.ts/', $file['name'], $matches);
        $num = isset($matches[1]) ? intval($matches[1]) : 0;
        
        $segments[] = [
            'name' => $file['name'],
            'url' => $file['download_url'],
            'num' => $num,
            'size' => $file['size'] ?? 0
        ];
    }
}

// ترتيب حسب الرقم
usort($segments, function($a, $b) {
    return $a['num'] - $b['num'];
});

$total = count($segments);

if ($total === 0) {
    http_response_code(503);
    echo json_encode(["error" => "No TS files found"]);
    exit;
}

// اختيار أحدث المقاطع
$wanted = array_slice($segments, -min($max_segments, $total), $max_segments);
$sequence = max(0, $total - count($wanted));

// إرسال الـ M3U8
header("Content-Type: application/vnd.apple.mpegurl");
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: *");

// بناء الـ M3U8
echo "#EXTM3U\n";
echo "#EXT-X-VERSION:3\n";
echo "#EXT-X-TARGETDURATION:10\n";
echo "#EXT-X-MEDIA-SEQUENCE:$sequence\n";
echo "#EXT-X-PLAYLIST-TYPE:EVENT\n\n";

foreach ($wanted as $seg) {
    // حساب المدة تقريباً من حجم الملف
    $duration = 10.0;
    if ($seg['size'] > 0) {
        $duration = max(5.0, min(15.0, $seg['size'] / 500000));
    }
    
    echo "#EXTINF:" . number_format($duration, 3) . ",\n";
    echo $seg['url'] . "\n";
}

// نهاية القائمة (للبث المباشر، لا نضيف #EXT-X-ENDLIST)
// echo "#EXT-X-ENDLIST\n";

// تسجيل بسيط
$log = date('Y-m-d H:i:s') . " - عرض " . count($wanted) . "/$total مقاطع\n";
@file_put_contents("hls.log", $log, FILE_APPEND);
?>