<?php
declare(strict_types=1);

function app_base_path(string $path = ''): string
{
    $base = dirname(__DIR__);
    if ($path === '') {
        return $base;
    }

    return $base . '/' . ltrim($path, '/');
}

function app_data_path(string $path = ''): string
{
    return app_base_path('src/data' . ($path !== '' ? '/' . ltrim($path, '/') : ''));
}

function app_load_json_file(string $path): array
{
    if (!is_file($path)) {
        return [];
    }

    $content = file_get_contents($path);
    if ($content === false) {
        return [];
    }

    $decoded = json_decode($content, true);
    return is_array($decoded) ? $decoded : [];
}

function app_get_catalog_components(): array
{
    return app_load_json_file(app_data_path('components.json'));
}

function app_get_rack_templates(): array
{
    return app_load_json_file(app_data_path('rack-templates.json'));
}

function app_bootstrap_payload(): array
{
    return [
        'app' => [
            'name' => 'code.it Rack Planner',
            'environment' => defined('APP_ENV') ? APP_ENV : 'prod',
            'baseUrl' => $GLOBALS['app_base_url'] ?? '',
            'apiBaseUrl' => $GLOBALS['app_api_base'] ?? '',
            'projectDomainNote' => 'Current domain is a concept workspace only, not the final product domain.',
        ],
        'rackTemplates' => app_get_rack_templates(),
        'components' => app_get_catalog_components(),
        'pluginFormat' => [
            'version' => 1,
            'acceptedExtensions' => ['json'],
            'requiredKeys' => ['manifestVersion', 'name', 'version', 'components'],
        ],
    ];
}

