<?php
// m3u8_crawler.php - LL-HLS 또는 일반 HLS 자동 감지, 입력칸 유지

$playlist_content = '';
$chunklist_content = '';
$chunklist_url_display = '';
$ts_urls = [];
$ll_hls_url = '';
$ll_hls_status = '';
$m4v_urls = [];

if(isset($_POST['playlist_url'])){
    $playlist_url = trim($_POST['playlist_url']);

    // playlist.m3u8 가져오기
    $playlist_content = @file_get_contents($playlist_url);
    if($playlist_content === false){
        $playlist_content = '[ERROR] playlist.m3u8 가져오기 실패';
    }

    // playlist body에서 chunklist URL 찾기
    $lines = array_filter(array_map('trim', explode("\n", $playlist_content)), fn($l)=>$l && $l[0] != '#');
    $chunklist_rel = null;
    foreach($lines as $l){
        if(strpos(strtolower($l), 'chunklist') !== false || strtolower(substr($l,-5)) === '.m3u8'){
            $chunklist_rel = $l;
            break;
        }
    }

    if($chunklist_rel){
        $parsed_playlist = parse_url($playlist_url);
        $path_parts = explode('/', $parsed_playlist['path']);
        $base_path = implode('/', array_slice($path_parts, 0, -1));
        $chunklist_url = $parsed_playlist['scheme'] . '://' . $parsed_playlist['host'] . $base_path . '/' . $chunklist_rel;

        $chunklist_url_display = $chunklist_url;
        $chunklist_content = @file_get_contents($chunklist_url);
        if($chunklist_content === false){
            $chunklist_content = '[ERROR] chunklist.m3u8 가져오기 실패';
        } else {
            // TS 파일 목록 (일반 HLS용)
            $ts_lines = array_filter(array_map('trim', explode("\n", $chunklist_content)), fn($l)=>$l && $l[0]!='#' && strtolower(substr($l,-3))==='.ts');
            $ts_urls = array_map(fn($l)=> (strpos($l,'http')===0 ? $l : rtrim(dirname($chunklist_url), '/') . '/' . $l), $ts_lines);

            // LL-HLS 감지 및 URL 생성
            if(preg_match('/LAST-MSN=(\d+)/', $chunklist_content, $matches)) {
                $last_msn = $matches[1];
                $ll_hls_url = $chunklist_url . "?_HLS_msn={$last_msn}&_HLS_part=1";

                // LL-HLS 상태 확인
                $headers = @get_headers($ll_hls_url, 1);
                $ll_hls_status = $headers ? substr($headers[0],9,3) : 'ERR';
                $ll_hls_status = ($ll_hls_status>=200 && $ll_hls_status<300) ? '✔ 정상' : '✖ 오류';

                // LL-HLS m4v 파일 확인
                $ll_content = @file_get_contents($ll_hls_url);
                if($ll_content){
                    $m4v_lines = array_filter(array_map('trim', explode("\n", $ll_content)), fn($l)=>$l && $l[0]!='#' && strtolower(substr($l,-4))==='.m4v');
                    $m4v_urls = array_map(fn($l)=> (strpos($l,'http')===0 ? $l : rtrim(dirname($ll_hls_url), '/') . '/' . $l), $m4v_lines);
                }
            } else {
                // 일반 HLS인 경우 LL-HLS URL 비워두기
                $ll_hls_url = '';
                $ll_hls_status = '';
                $m4v_urls = [];
            }
        }
    }
}
?>

<!doctype html>
<html>
<head><meta charset="utf-8"><title>m3u8 Crawler</title></head>
<body>
<h2>m3u8 Crawler (PHP) - LL-HLS 또는 일반 HLS 자동 감지, 입력칸 유지</h2>
<form method="post">
  playlist.m3u8 URL: <input type="text" name="playlist_url" size="80" value="<?php echo isset($_POST['playlist_url']) ? htmlspecialchars($_POST['playlist_url']) : ''; ?>">
  <button type="submit">실행</button>
</form>

<?php if($playlist_content): ?>
<h3>playlist.m3u8</h3>
<div style="display:flex;gap:20px;">
  <pre style="flex:1"><?php echo htmlspecialchars($playlist_content); ?></pre>
  <textarea style="flex:1" readonly><?php echo htmlspecialchars($playlist_content); ?></textarea>
</div>
<?php endif; ?>

<?php if($chunklist_content): ?>
<h3>chunklist.m3u8</h3>
<div style="display:flex;gap:20px;">
  <pre style="flex:1"><?php echo htmlspecialchars($chunklist_content); ?></pre>
  <textarea style="flex:1" readonly><?php echo htmlspecialchars($chunklist_content); ?></textarea>
  <textarea style="flex:1" readonly><?php echo htmlspecialchars($chunklist_url_display); ?></textarea>
</div>
<?php endif; ?>

<?php if($ll_hls_url): ?>
<h3>LL-HLS URL</h3>
<div style="display:flex; gap:10px; align-items:center;">
  <textarea style="flex:1" readonly><?php echo $ll_hls_url; ?></textarea>
  <span style="font-weight:bold"><?php echo $ll_hls_status; ?></span>
</div>
<?php endif; ?>

<?php if($m4v_urls): ?>
<h3>LL-HLS m4v 파일 확인</h3>
<ul>
<?php foreach($m4v_urls as $m4v):
    $headers = @get_headers($m4v, 1);
    $status = $headers ? substr($headers[0],9,3) : 'ERR';
    $size = isset($headers['Content-Length']) ? $headers['Content-Length'] : '-';
    $ok = ($status>=200 && $status<300) ? '✔' : '✖';
?>
<li><?php echo "$ok $m4v (status: $status, size: $size)"; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>

<?php if($ts_urls): ?>
<h3>TS 파일 확인</h3>
<ul>
<?php foreach($ts_urls as $ts):
    $headers = @get_headers($ts, 1);
    $status = $headers ? substr($headers[0],9,3) : 'ERR';
    $size = isset($headers['Content-Length']) ? $headers['Content-Length'] : '-';
    $ok = ($status>=200 && $status<300) ? '✔' : '✖';
    $body = @file_get_contents($ts);
    $body_preview = $body ? htmlspecialchars(substr($body,0,200)) : '[ERROR] 가져오기 실패';
?>
<li><?php echo "$ok $ts (status: $status, size: $size)"; ?>
<div style="display:flex;gap:20px; margin-top:5px;">
  <pre style="flex:1"><?php echo $body_preview; ?></pre>
  <textarea style="flex:1" readonly><?php echo $body_preview; ?></textarea>
</div>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>

</body>
</html>
