<?php
declare(strict_types=1);

use App\Avatar\Lorelei;

$allowedVariantParams = ['eyesVariant', 'eyebrowsVariant', 'mouthVariant', 'glassesVariant', 'hairVariant', 'beardVariant', 'earringsVariant'];
$allowedProbabilityParams = ['glassesProbability', 'hairProbability', 'beardProbability', 'earringsProbability'];
$seed = Lorelei::normalizeSeed((string)($_GET['seed'] ?? 'papa-kind-treff'));
$cacheDir = dirname(__DIR__, 3) . '/assets/avatars/dicebear-cache';

if (!is_dir($cacheDir)) {
    @mkdir($cacheDir, 0775, true);
}

$query = ['seed' => $seed, 'size' => '256'];
foreach ($allowedVariantParams as $param) {
    $value = Lorelei::normalizeVariant((string)($_GET[$param] ?? ''));
    if ($value !== '') {
        $query[$param] = $value;
    }
}

foreach ($allowedProbabilityParams as $param) {
    $rawValue = (string)($_GET[$param] ?? '');
    if ($rawValue === '') {
        continue;
    }

    $value = max(0, min(100, (int) $rawValue));
    $query[$param] = (string) $value;
}

$cacheKey = sha1(json_encode($query, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?: $seed);
$cacheFile = $cacheDir . '/' . $cacheKey . '.svg';
$svg = is_file($cacheFile) ? file_get_contents($cacheFile) : false;

if ($svg === false) {
    $url = 'https://api.dicebear.com/10.x/lorelei/svg?' . http_build_query($query);
    $context = stream_context_create([
        'http' => [
            'method' => 'GET',
            'timeout' => 6,
            'header' => "User-Agent: Papa-Kind-Treff/1.0\r\nAccept: image/svg+xml\r\n",
        ],
    ]);

    $remote = @file_get_contents($url, false, $context);
    if (is_string($remote) && str_contains($remote, '<svg')) {
        $svg = $remote;
        @file_put_contents($cacheFile, $svg);
    }
}

if (!is_string($svg) || $svg === '') {
    $svg = Lorelei::fallbackSvg($seed, 'Avatar');
}

header('Content-Type: image/svg+xml; charset=utf-8');
header('Cache-Control: public, max-age=604800, immutable');
echo $svg;
