#!/usr/bin/env node
/**
 * Sign a license manifest JSON and write a .license file.
 *
 * Usage:
 *   node scripts/sign-license-manifest.js --template license/manifest-template.json --out license/sovereign.license
 *   SOVEREIGN_LICENSE_PRIVATE_KEY_PATH=delivery/sovereign-license-root.pem node scripts/sign-license-manifest.js ...
 */
'use strict';

const fs = require('fs');
const path = require('path');
const {
  signManifest,
  getLocalHardwareFingerprint,
} = require('../src/api/lib/licenseManifest');

function arg(name, fallback) {
  const i = process.argv.indexOf(name);
  return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback;
}

const templatePath = arg('--template', path.join(__dirname, '../license/manifest-rhoylle-unlimited.json'));
const outPath = arg('--out', path.join(__dirname, '../license/rhoylle.lifetime.license'));
const privPath = (process.env.SOVEREIGN_LICENSE_PRIVATE_KEY_PATH || '').trim()
  || path.join(__dirname, '../delivery/sovereign-license-root.pem');

if (!fs.existsSync(templatePath)) {
  console.error('Template not found:', templatePath);
  process.exit(1);
}
if (!fs.existsSync(privPath)) {
  console.error('Private key not found:', privPath);
  console.error('Run: node scripts/generate-license-keys.js');
  process.exit(1);
}

const manifest = JSON.parse(fs.readFileSync(templatePath, 'utf8'));
manifest.manifestVersion = manifest.manifestVersion || 1;
manifest.issuedAt = manifest.issuedAt || new Date().toISOString();
if (manifest.bindHardware && !manifest.hardwareFingerprint) {
  manifest.hardwareFingerprint = getLocalHardwareFingerprint();
}
delete manifest.bindHardware;

const privateKeyPem = fs.readFileSync(privPath, 'utf8');
manifest.signature = signManifest(manifest, privateKeyPem);

fs.mkdirSync(path.dirname(outPath), { recursive: true });
fs.writeFileSync(outPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
console.log('Signed license written:', outPath);
console.log('  licenseId:', manifest.licenseId);
console.log('  tier:', manifest.tier);
console.log('  expiresAt:', manifest.expiresAt || 'never');
