import { cpSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { dirname, join, relative, sep } from 'node:path';
import { fileURLToPath } from 'node:url';
import { shouldSkipStagingEntry } from './prepare-git-staging.mjs';

const root = dirname(dirname(fileURLToPath(import.meta.url)));
const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
const version = pkg.version;
const outputRoot = join(root, 'release-output');
const packageName = `Vendoo_${version}`;
const stage = join(outputRoot, packageName);
const normalize = value => value.split(sep).join('/');

rmSync(outputRoot, { recursive: true, force: true });
mkdirSync(stage, { recursive: true });

function copyTree(src, dest, rel = '') {
  for (const name of readdirSync(src)) {
    const source = join(src, name);
    const childRel = rel ? join(rel, name) : name;
    const stat = lstatSync(source);
    if (shouldSkipStagingEntry(childRel, stat)) continue;
    const target = join(dest, name);
    if (stat.isDirectory()) {
      mkdirSync(target, { recursive: true });
      copyTree(source, target, childRel);
    } else if (stat.isFile()) {
      mkdirSync(dirname(target), { recursive: true });
      cpSync(source, target);
    }
  }
}
copyTree(root, stage);

const checksums = [];
function hashTree(dir) {
  for (const name of readdirSync(dir).sort((a, b) => a.localeCompare(b))) {
    const abs = join(dir, name);
    const stat = lstatSync(abs);
    if (stat.isDirectory()) hashTree(abs);
    else {
      const rel = normalize(relative(stage, abs));
      if (rel === 'FILE_CHECKSUMS_SHA256.txt') continue;
      const digest = createHash('sha256').update(readFileSync(abs)).digest('hex');
      checksums.push(`${digest}  ${rel}`);
    }
  }
}
hashTree(stage);
writeFileSync(join(stage, 'FILE_CHECKSUMS_SHA256.txt'), checksums.join('\n') + '\n', 'utf8');
writeFileSync(join(outputRoot, 'RELEASE_NAME.txt'), packageName + '\n', 'utf8');
console.log(`Release-Staging erstellt: ${stage}`);
console.log(`${checksums.length} Dateien mit SHA-256 erfasst.`);
