<?php
declare(strict_types=1);
require __DIR__ . '/../lib/bootstrap.php';
handle_cors_preflight();
require_method(['GET']);
rate_limit('text-proxy', 90, 60);

$device = device_from_signed_token('proxy');
require_active_device($device);
$target = validate_proxy_url(trim((string) ($_GET['url'] ?? '')), $device, true);

if (!function_exists('curl_init')) {
    json_response(['ok' => false, 'error' => 'Proxy service is unavailable'], 503);
}

$body = '';
$maxBytes = max(1024, (int) config('proxy.max_text_bytes', 8 * 1024 * 1024));
$ch = curl_init($target['url']);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => false,
    CURLOPT_FOLLOWLOCATION => false,
    CURLOPT_CONNECTTIMEOUT => 8,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS,
    CURLOPT_RESOLVE => curl_resolve_entries($target),
    CURLOPT_USERAGENT => 'NexoPlayer/2.0',
    CURLOPT_HTTPHEADER => ['Accept: application/json, application/xml, application/x-mpegURL, text/plain, text/html, */*'],
    CURLOPT_WRITEFUNCTION => static function ($curl, string $chunk) use (&$body, $maxBytes): int {
        if (strlen($body) + strlen($chunk) > $maxBytes) {
            return 0;
        }
        $body .= $chunk;
        return strlen($chunk);
    },
]);
$ok = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$contentType = (string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
curl_close($ch);

if ($ok === false || $status < 200 || $status >= 300 || $body === '') {
    json_response(['ok' => false, 'error' => 'Could not fetch remote content'], 502);
}

apply_cors_headers();
header('Content-Type: ' . ($contentType ?: 'text/plain; charset=utf-8'));
header('Cache-Control: private, max-age=120');
header('X-Content-Type-Options: nosniff');
echo $body;
