<?php
declare(strict_types=1);

ob_start();

header('Content-Type: application/json');
header('Cache-Control: no-store');

function jsonError(string $message, int $code = 400): void {
    ob_clean();
    http_response_code($code);
    echo json_encode(['image_url' => null, 'fallback_level' => null, 'error' => $message]);
    exit;
}

try {
    require_once __DIR__ . '/includes/config.php';
    require_once __DIR__ . '/includes/scraper.php';

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        jsonError('POST required', 405);
    }

    $raw  = file_get_contents('php://input');
    $data = json_decode($raw ?: '{}', true) ?? [];
    $url  = trim($data['url'] ?? '');

    if (empty($url)) {
        jsonError('URL is required');
    }

    if (!filter_var($url, FILTER_VALIDATE_URL)) {
        jsonError('URL invalide — vérifie qu\'elle commence par https://');
    }

    if (!function_exists('curl_init')) {
        jsonError('cURL non disponible sur ce serveur');
    }

    $timeout = isset($data['timeout']) ? (int)$data['timeout'] : DEFAULT_TIMEOUT;
    $scraper = new Scraper($timeout, DEFAULT_USER_AGENT, 2, 0);
    $result  = $scraper->extract($url);

    ob_clean();
    echo json_encode([
        'image_url'      => $result['image_url'],
        'fallback_level' => $result['fallback_level'],
        'error'          => $result['error'],
        'source_url'     => $url,
    ]);

} catch (Throwable $e) {
    jsonError('Erreur serveur : ' . $e->getMessage(), 500);
}
