#!/usr/bin/env node
/**
 * Build multi-OS release artifacts + manifest for data-driven download portal.
 * Usage: node scripts/build-release-artifacts.js
 */
'use strict';

const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

const root = path.resolve(__dirname, '..');
const version = fs.readFileSync(path.join(root, 'VERSION'), 'utf8').trim();
const releaseRoot = path.join(root, 'releases');
const staging = path.join(releaseRoot, '_staging', version);

function rmrf(p) {
  if (fs.existsSync(p)) fs.rmSync(p, { recursive: true, force: true });
}

function copyDir(src, dest, skip = ['node_modules', 'build', '.git']) {
  if (!fs.existsSync(src)) return;
  fs.mkdirSync(dest, { recursive: true });
  for (const ent of fs.readdirSync(src, { withFileTypes: true })) {
    if (skip.includes(ent.name)) continue;
    const s = path.join(src, ent.name);
    const d = path.join(dest, ent.name);
    if (ent.isDirectory()) copyDir(s, d, skip);
    else fs.copyFileSync(s, d);
  }
}

function sha256File(fp) {
  const h = crypto.createHash('sha256');
  h.update(fs.readFileSync(fp));
  return h.digest('hex');
}

function writeInstallScripts(baseDir) {
  const win = `@echo off
REM DBAOps Sovereign - Windows installer (${version})
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0scripts\\install.ps1"
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0scripts\\bootstrap-all.ps1"
echo.
echo Open http://localhost:3000 after API starts on port 3041.
`;
  fs.writeFileSync(path.join(baseDir, 'INSTALL.bat'), win);

  const sh = `#!/bin/sh
set -e
echo "DBAOps Sovereign - installer ${version}"
chmod +x scripts/install.sh scripts/run.sh scripts/migrate.sh 2>/dev/null || true
./scripts/install.sh
./scripts/migrate.sh
echo "Run: ./scripts/run.sh  then open http://localhost:3000"
`;
  fs.writeFileSync(path.join(baseDir, 'INSTALL.sh'), sh, { mode: 0o755 });
}

function stagePlatform(platform) {
  const dir = path.join(staging, platform);
  rmrf(dir);
  fs.mkdirSync(dir, { recursive: true });

  for (const f of ['VERSION', 'README.md', 'CHANGELOG.md', '.env.example', 'package.json', 'docker-compose.yml', 'docker-compose.all-in-one.yml']) {
    const p = path.join(root, f);
    if (fs.existsSync(p)) fs.copyFileSync(p, path.join(dir, f));
  }
  copyDir(path.join(root, 'delivery'), path.join(dir, 'delivery'));
  copyDir(path.join(root, 'docs'), path.join(dir, 'docs'));
  copyDir(path.join(root, 'scripts'), path.join(dir, 'scripts'));
  copyDir(path.join(root, 'docker'), path.join(dir, 'docker'));
  copyDir(path.join(root, 'src/collectors'), path.join(dir, 'src/collectors'));
  fs.mkdirSync(path.join(dir, 'src/database'), { recursive: true });
  copyDir(path.join(root, 'src/database'), path.join(dir, 'src/database'));
  if (fs.existsSync(path.join(root, 'license'))) {
    copyDir(path.join(root, 'license'), path.join(dir, 'license'));
  }
  writeInstallScripts(dir);
  return dir;
}

function packDir(srcDir, outPath, asZip) {
  fs.mkdirSync(path.dirname(outPath), { recursive: true });
  if (asZip) {
    execSync(
      `powershell -NoProfile -Command "Compress-Archive -Path '${srcDir.replace(/'/g, "''")}\\*' -DestinationPath '${outPath.replace(/'/g, "''")}' -Force"`,
      { stdio: 'inherit' }
    );
  } else {
    execSync(`tar -czf "${outPath}" -C "${srcDir}" .`, { stdio: 'inherit' });
  }
}

function buildArtifact(platform, arch, asZip, fileName) {
  const src = stagePlatform(platform);
  const outDir = path.join(releaseRoot, 'sovereign-platform', version);
  fs.mkdirSync(outDir, { recursive: true });
  const outPath = path.join(outDir, fileName);
  packDir(src, outPath, asZip);
  const stat = fs.statSync(outPath);
  return {
    productCode: 'sovereign-platform',
    platform,
    architecture: arch,
    packageType: asZip ? 'zip' : 'tar.gz',
    fileName,
    storagePath: path.join('sovereign-platform', version, fileName).replace(/\\/g, '/'),
    sha256: sha256File(outPath),
    fileSizeBytes: stat.size,
    installCommand: platform === 'windows' ? 'INSTALL.bat' : './INSTALL.sh',
  };
}

function buildCollectorZip() {
  const dir = path.join(staging, 'collector-win');
  rmrf(dir);
  fs.mkdirSync(dir, { recursive: true });
  copyDir(path.join(root, 'src/collectors'), path.join(dir, 'collectors'));
  fs.copyFileSync(path.join(root, 'VERSION'), path.join(dir, 'VERSION'));
  fs.writeFileSync(path.join(dir, 'README.txt'), `DBAOps Sovereign Collector ${version}\n`);
  const outDir = path.join(releaseRoot, 'sovereign-collector', version);
  fs.mkdirSync(outDir, { recursive: true });
  const fileName = `DBAOps-Sovereign-${version}-collector-windows-x64.zip`;
  const outPath = path.join(outDir, fileName);
  packDir(dir, outPath, true);
  const stat = fs.statSync(outPath);
  return {
    productCode: 'sovereign-collector',
    platform: 'windows',
    architecture: 'x64',
    packageType: 'zip',
    fileName,
    storagePath: path.join('sovereign-collector', version, fileName).replace(/\\/g, '/'),
    sha256: sha256File(outPath),
    fileSizeBytes: stat.size,
    installCommand: 'powershell -File collectors\\DBAOps-Sovereign-Collector.ps1 -SubmitAll',
  };
}

console.log(`[build-releases] DBAOps Sovereign ${version}`);
rmrf(path.join(releaseRoot, '_staging'));

const artifacts = [
  buildArtifact('windows', 'x64', true, `DBAOps-Sovereign-${version}-windows-x64.zip`),
  buildArtifact('linux', 'x64', false, `DBAOps-Sovereign-${version}-linux-x64.tar.gz`),
  buildArtifact('macos', 'universal', false, `DBAOps-Sovereign-${version}-macos-universal.tar.gz`),
  buildCollectorZip(),
];

const manifest = {
  version,
  builtAt: new Date().toISOString(),
  vendor: 'RHOYLLE INNOVATION EMPIRE LLC',
  releases: [
    {
      productCode: 'sovereign-platform',
      version,
      channel: 'pilot',
      title: `DBAOps Sovereign Platform ${version}`,
      releaseNotes: 'Full console + API + collectors + enterprise delivery pack. SHA-256 verified downloads.',
      minLicenseTier: null,
      artifacts: artifacts.filter((a) => a.productCode === 'sovereign-platform'),
    },
    {
      productCode: 'sovereign-collector',
      version,
      channel: 'pilot',
      title: `DBAOps Sovereign Collector ${version}`,
      releaseNotes: 'Windows PowerShell fleet collector for telemetry, security, and compliance facts.',
      minLicenseTier: null,
      artifacts: artifacts.filter((a) => a.productCode === 'sovereign-collector'),
    },
  ],
};

fs.mkdirSync(releaseRoot, { recursive: true });
fs.writeFileSync(path.join(releaseRoot, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
console.log(`[build-releases] ${artifacts.length} artifacts → ${releaseRoot}`);
for (const a of artifacts) {
  console.log(`  ${a.fileName}  ${(a.fileSizeBytes / 1024 / 1024).toFixed(2)} MB  sha256:${a.sha256.slice(0, 16)}…`);
}
