#!/usr/bin/env php
<?php

declare(strict_types=1);

/**
 * @param array<string, mixed> $srcDoc
 * @param array<string, mixed> $nextDoc
 *
 * @return array<string, mixed>
 */
function merge_openapi(array $srcDoc, array $nextDoc): array
{
    $srcDoc['paths'] = \array_merge($srcDoc['paths'], $nextDoc['paths']);

    if (!isset($srcDoc['components'])) {
        $srcDoc['components'] = [];
    }
    $componentsKeys = ['schemas', 'responses', 'parameters', 'examples', 'requestBodies', 'headers', 'securitySchemes'];
    foreach ($componentsKeys as $key) {
        $srcDoc['components'][$key] = ($srcDoc['components'][$key] ?? []) + ($nextDoc['components'][$key] ?? []);
    }
    $srcDoc['security'] = \array_merge($srcDoc['security'] ?? [], $nextDoc['security'] ?? []);
    $srcDoc['tags'] = \array_merge($srcDoc['tags'] ?? [], $nextDoc['tags'] ?? []);

    return $srcDoc;
}

if ('cli' !== \PHP_SAPI) {
    echo 'This script must be run from command line';

    return 1;
}

$configDir = __DIR__.'/../config/';
$configFiles = \array_values(
    \array_filter(
        \scandir($configDir),
        fn ($configFile) => \is_file($configDir.$configFile) && \str_ends_with($configFile, 'json') && 'all.json' !== $configFile,
    ),
);

echo 'Merging '.\count($configFiles)." files\n";
foreach ($configFiles as $configFile) {
    echo "\t - ".$configFile."\n";
}

$doc = \json_decode(\file_get_contents($configDir.$configFiles[0]), true);
for ($i = 1; $i < \count($configFiles); ++$i) {
    $nextDoc = \json_decode(\file_get_contents($configDir.$configFiles[$i]), true);

    $doc = \merge_openapi($doc, $nextDoc);
}

$doc['info'] = [
    'version' => '1.0.0',
    'title' => 'Reef API',
    'description' => 'Access all Reef APIs',
];

\file_put_contents($configDir.'all.json', \json_encode($doc, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES));
