<?php
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');

$baseDir = __DIR__;
$baseUrl = '/assets/chat-media';

function slugify_label(string $value): string {
    $value = trim($value);
    if ($value === '') return 'Untitled';
    $value = preg_replace('/[_-]+/', ' ', $value);
    $value = preg_replace('/\s+/', ' ', $value);
    return ucwords(trim($value));
}

function infer_category(string $relativePath, string $filename, array $allowed): string {
    $relativePath = strtolower(trim(str_replace('\\', '/', $relativePath), '/'));
    $filename = strtolower($filename);
    if ($relativePath !== '') {
        $parts = explode('/', $relativePath);
        foreach ($parts as $part) {
            $part = preg_replace('/[^a-z0-9_-]/', '', $part);
            if (isset($allowed[$part])) return $part;
        }
    }
    foreach ($allowed as $key => $_label) {
        if (preg_match('/(^|[^a-z])' . preg_quote($key, '/') . '([^a-z]|$)/', $filename)) {
            return $key;
        }
    }
    if (preg_match('/dj|mix|deck|turntable|vinyl|headphone|mic|studio|record/', $filename)) return 'music';
    if (preg_match('/dance|club|disco|party|crowd|rave/', $filename)) return 'party';
    if (preg_match('/live|radio|air|request|broadcast/', $filename)) return 'radio';
    if (preg_match('/love|heart|kiss/', $filename)) return 'love';
    if (preg_match('/night|moon|late|dark|neon/', $filename)) return 'night';
    if (preg_match('/hype|wow|cheer|letsgo|go|boom/', $filename)) return 'hype';
    return 'all';
}

function keywordize(string $label, string $category, string $filename): string {
    $base = strtolower($label . ' ' . $category . ' ' . preg_replace('/[^a-z0-9]+/i', ' ', $filename));
    $extra = ' radio music dance party dj live request broadcast on air underground fx';
    return trim(preg_replace('/\s+/', ' ', $base . $extra));
}

function scan_media(string $type, array $allowedCategories): array {
    global $baseDir, $baseUrl;
    $dir = $baseDir . '/' . $type;
    $items = [];
    $foundCategories = ['all' => 'All'];
    if (!is_dir($dir)) {
        return ['items' => [], 'categories' => [['id' => 'all', 'label' => 'All']]];
    }

    $rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS));
    foreach ($rii as $file) {
        if (!$file->isFile()) continue;
        $ext = strtolower($file->getExtension());
        if (!in_array($ext, ['png','jpg','jpeg','gif','webp','svg'], true)) continue;
        $fullPath = $file->getPathname();
        $relativePath = str_replace('\\', '/', substr($fullPath, strlen($dir)));
        $relativePath = ltrim($relativePath, '/');
        $pathParts = explode('/', $relativePath);
        $filename = array_pop($pathParts);
        $stem = pathinfo($filename, PATHINFO_FILENAME);
        $folderPath = implode('/', $pathParts);
        $category = infer_category($folderPath, $stem, $allowedCategories);
        if ($category !== 'all' && isset($allowedCategories[$category])) $foundCategories[$category] = $allowedCategories[$category];
        $items[] = [
            'src' => $baseUrl . '/' . $type . '/' . str_replace('%2F', '/', rawurlencode($relativePath)),
            'label' => slugify_label($stem),
            'category' => $category,
            'keywords' => keywordize(slugify_label($stem), $category, $stem),
        ];
    }

    usort($items, function($a, $b) {
        return strnatcasecmp($a['label'], $b['label']);
    });

    $categories = [];
    foreach ($foundCategories as $id => $label) {
        $categories[] = ['id' => $id, 'label' => $label];
    }

    return ['items' => $items, 'categories' => $categories];
}

$categoryLabels = [
    'radio' => 'Radio',
    'music' => 'Music',
    'dance' => 'Dance',
    'party' => 'Party',
    'hype' => 'Hype',
    'night' => 'Night',
    'requests' => 'Requests',
    'love' => 'Love',
    'reactions' => 'Reactions',
    'dj' => 'DJ',
    'crowd' => 'Crowd',
    'club' => 'Club'
];

$stickers = scan_media('stickers', $categoryLabels);
$gifs = scan_media('gifs', $categoryLabels);

echo json_encode([
    'version' => 3,
    'generated_at' => gmdate('c'),
    'sticker_categories' => $stickers['categories'],
    'gif_categories' => $gifs['categories'],
    'stickers' => $stickers['items'],
    'gifs' => $gifs['items'],
], JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
