<?php

declare(strict_types=1);

require dirname(__DIR__) . '/app/bootstrap.php';

$config = require APP_PATH . '/config.php';
$manager = new \App\Services\License\LicenseManager($config);
$path = APP_BASE_PATH . '/storage/license/dev-override.json';

$raw = @file_get_contents($path);
if ($raw === false) {
    fwrite(STDERR, "dev-override.json not found at {$path}\n");
    exit(1);
}

$doc = json_decode($raw, true);
if (!is_array($doc)) {
    fwrite(STDERR, "dev-override.json is not valid JSON\n");
    exit(1);
}

$privateKeyB64 = getenv('LICENSE_PRIVATE_KEY_B64') ?: '';
if ($privateKeyB64 === '') {
    $privateKeyPath = APP_BASE_PATH . '/storage/license/private.key';
    if (is_file($privateKeyPath)) {
        $privateKeyB64 = trim((string) file_get_contents($privateKeyPath));
    }
}
if ($privateKeyB64 === '') {
    fwrite(STDERR, "Set LICENSE_PRIVATE_KEY_B64 or create storage/license/private.key first.\n");
    exit(1);
}

$privateKey = base64_decode($privateKeyB64, true);
if ($privateKey === false) {
    fwrite(STDERR, "LICENSE_PRIVATE_KEY_B64 is not valid base64.\n");
    exit(1);
}

if (!function_exists('sodium_crypto_sign_detached')) {
    fwrite(STDERR, "libsodium is required to sign dev override documents.\n");
    exit(1);
}

$doc['signature'] = base64_encode(sodium_crypto_sign_detached($manager->canonicalPayload($doc), $privateKey));
file_put_contents($path, json_encode($doc, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL, LOCK_EX);

echo "Dev override signed successfully: {$path}\n";
