<?php

declare(strict_types=1);

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

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

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

$license = json_decode($raw, true);
if (!is_array($license)) {
    fwrite(STDERR, "license.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);
}

$payload = $manager->canonicalPayload($license);
if (function_exists('sodium_crypto_sign_detached')) {
    $signature = sodium_crypto_sign_detached($payload, $privateKey);
} else {
    fwrite(STDERR, "libsodium is required to sign licenses with this script.\n");
    exit(1);
}

$license['signature'] = base64_encode($signature);
file_put_contents($licensePath, json_encode($license, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL, LOCK_EX);

echo "License signed successfully: {$licensePath}\n";
