<?php
/**
 * Managed catalog API endpoint.
 * Served at /api/managed-stations.json via .htaccess rewrite.
 * Returns the same JSON envelope used by the Vite dev/preview middleware:
 * { schemaVersion, updatedAt, stations }.
 */

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-cache');

$catalogPath = __DIR__ . '/../stations.json';

if (!is_file($catalogPath)) {
    http_response_code(404);
    echo json_encode(['error' => 'Catalog not found']);
    exit;
}

$raw = file_get_contents($catalogPath);
if ($raw === false) {
    http_response_code(500);
    echo json_encode(['error' => 'Failed to read catalog']);
    exit;
}

$data = json_decode($raw, true);
if ($data === null) {
    http_response_code(500);
    echo json_encode(['error' => 'Invalid catalog JSON']);
    exit;
}

// Accept both plain array and already-enveloped format
$stations = isset($data['stations']) ? $data['stations'] : $data;

$envelope = [
    'schemaVersion' => 1,
    'updatedAt'     => date('c', filemtime($catalogPath)),
    'stations'      => $stations,
];

echo json_encode($envelope, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
