<?php
define('WP_USE_THEMES', false);
require('../../../wp-load.php');

echo "=== Testing YouTube Video ID Extraction ===\n\n";

$url = 'https://www.youtube.com/@NashvilleBirdCam/streams';
echo "Fetching: $url\n\n";

$response = wp_remote_get($url, array(
    'timeout' => 10,
    'redirection' => 5,
    'user-agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
    'headers' => array(
        'Accept-Language' => 'en-US,en;q=0.9,de;q=0.8',
    ),
));

if (is_wp_error($response)) {
    echo "ERROR: " . $response->get_error_message() . "\n";
    exit;
}

$body = wp_remote_retrieve_body($response);
echo "Response size: " . strlen($body) . " bytes\n\n";

// Test all patterns
$patterns = array(
    'watchEndpoint' => '/"watchEndpoint":\{"videoId":"([A-Za-z0-9_-]{11})"/i',
    'videoId with isLiveNow' => '/"videoId":"([A-Za-z0-9_-]{11})"[^}]*"isLiveNow":true/i',
    'URL with u0026' => '/\/watch\?v=([A-Za-z0-9_-]{11})\\u0026/i',
    'URL standard' => '/\/watch\?v=([A-Za-z0-9_-]{11})/i',
    'LIVE_NOW label' => '/LIVE_NOW.*?"videoId":"([A-Za-z0-9_-]{11})"/is',
);

echo "Testing patterns:\n";
foreach ($patterns as $name => $pattern) {
    if (preg_match($pattern, $body, $m)) {
        echo "✓ $name: MATCH - video_id = " . $m[1] . "\n";
    } else {
        echo "✗ $name: NO MATCH\n";
    }
}

echo "\n=== Calling mm_video_extract_youtube_live_video_id ===\n";
$video_id = mm_video_extract_youtube_live_video_id($body);
if ($video_id) {
    echo "✓ Extracted video_id: $video_id\n";
} else {
    echo "✗ NO video_id extracted!\n";
}

// Show some context
echo "\n=== Searching for 'watchEndpoint' in response ===\n";
if (preg_match('/"watchEndpoint":\{"videoId":"[^"]+"/i', $body, $context)) {
    echo "Found: " . $context[0] . "\n";
} else {
    echo "Not found\n";
}

echo "\n=== Searching for 'PAmS12qbdzA' (known live video ID) ===\n";
if (strpos($body, 'PAmS12qbdzA') !== false) {
    echo "✓ Found PAmS12qbdzA in response\n";
    
    // Get context around it
    $pos = strpos($body, 'PAmS12qbdzA');
    $start = max(0, $pos - 100);
    $context = substr($body, $start, 250);
    echo "Context: " . htmlspecialchars($context) . "\n";
} else {
    echo "✗ PAmS12qbdzA NOT found in response\n";
}
