/**
 * Owner-only release bump: fingerprint the tree, bump VERSION deterministically,
 * append release.json, and write releases/<version>.zip.
 *
 *   npm run release
 */
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
  LARGE_THRESHOLD_KB,
  bumpVersion,
  buildReleaseZip,
  fingerprintTree,
  readReleaseFile,
  sha256File,
  writeReleaseFile,
  writeVersionFile,
} from '../src/server/update';
import { VERSION as CURRENT } from '../src/version';

const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');

function main(): void {
  const before = fingerprintTree(ROOT);
  const file = readReleaseFile(ROOT);
  const prev = file.history.length
    ? [...file.history].sort((a, b) => a.publishedAt.localeCompare(b.publishedAt)).at(-1)
    : null;

  let next: string;
  if (!prev) {
    next = CURRENT;
    console.log(`  baseline release ${next} (no prior history)`);
  } else {
    const deltaKB = Math.abs(before.sizeKB - prev.sizeKB);
    const kind = deltaKB >= LARGE_THRESHOLD_KB ? 'letter' : 'hundredths';
    next = bumpVersion(prev.version, kind);
    console.log(`  delta ${deltaKB} KB (threshold ${LARGE_THRESHOLD_KB}) → ${kind} bump: ${prev.version} → ${next}`);
    writeVersionFile(ROOT, next);
  }

  const finalFp = fingerprintTree(ROOT);
  const zipPath = buildReleaseZip(ROOT, next);
  const zipHash = sha256File(zipPath);

  const entry = {
    version: next,
    hash: zipHash,
    sizeKB: finalFp.sizeKB,
    publishedAt: new Date().toISOString(),
    artifact: path.relative(ROOT, zipPath).split(path.sep).join('/'),
  };

  const history = file.history.filter(h => h.version !== next);
  history.push(entry);
  writeReleaseFile(ROOT, { history });

  console.log(`  wrote ${entry.artifact}`);
  console.log(`  hash  ${entry.hash}`);
  console.log(`  size  ${entry.sizeKB} KB`);
  console.log(`  release.json updated — approve fleet upgrade from the owner admin panel when ready.`);
}

main();
