<?php

declare(strict_types=1);

require_once __DIR__ . '/bootstrap.php';

$configFile = APP_CONFIG_PATH . '/api.php';

if (!is_file($configFile)) {
    http_response_code(500);
    exit('File _app/config/api.php tidak ditemukan.');
}

try {
    $apiConfig = require $configFile;
} catch (Throwable $e) {
    error_log(
        'API config error: ' . $e->getMessage()
    );

    http_response_code(500);

    exit(
        'Konfigurasi API gagal dimuat: ' .
        htmlspecialchars(
            $e->getMessage(),
            ENT_QUOTES,
            'UTF-8'
        )
    );
}

if (!is_array($apiConfig)) {
    http_response_code(500);
    exit('Konfigurasi API bukan array.');
}

function configStatus(array $config, array $secretFields)
{
    $result = [
        'url_valid' => false,
        'https'     => false,
        'credentials_ready' => true,
    ];

    $baseUrl = isset($config['base_url'])
        ? trim((string) $config['base_url'])
        : '';

    $result['url_valid'] = (
        $baseUrl !== '' &&
        filter_var($baseUrl, FILTER_VALIDATE_URL) !== false
    );

    $result['https'] = (
        strtolower(
            (string) parse_url(
                $baseUrl,
                PHP_URL_SCHEME
            )
        ) === 'https'
    );

    foreach ($secretFields as $field) {
        $value = isset($config[$field])
            ? trim((string) $config[$field])
            : '';

        if (
            $value === '' ||
            stripos($value, 'ISI_') === 0
        ) {
            $result['credentials_ready'] = false;
        }
    }

    return $result;
}

$output = [
    'success' => true,
    'message' => 'Konfigurasi API berhasil dimuat.',

    'sgx' => configStatus(
        isset($apiConfig['sgx'])
            ? $apiConfig['sgx']
            : [],
        [
            'agent_code',
            'signature',
        ]
    ),

    'nexus' => configStatus(
        isset($apiConfig['nexus'])
            ? $apiConfig['nexus']
            : [],
        [
            'agent_code',
            'agent_token',
        ]
    ),

    'security' => [
        'signature_exposed'   => false,
        'agent_token_exposed' => false,
    ],

    'php_version' => PHP_VERSION,
];

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
header('X-Content-Type-Options: nosniff');

echo json_encode(
    $output,
    JSON_PRETTY_PRINT |
    JSON_UNESCAPED_UNICODE |
    JSON_UNESCAPED_SLASHES
);