const fs = require("fs");
const path = require("path");
const { spawnSync } = require("child_process");

const root = path.resolve(__dirname, "..");
const app = path.join(root, "app");
const output = path.join(root, "build");
const stage = path.join(output, "app");
const include = ["index.html", "config.xml", "1000.jpg", "512.png", "assets", "css", "images", "js"];

fs.rmSync(stage, { recursive: true, force: true });
fs.mkdirSync(stage, { recursive: true });
for (const name of include) {
    const source = path.join(app, name);
    if (fs.existsSync(source)) fs.cpSync(source, path.join(stage, name), { recursive: true });
}

for (const stale of ["js/main.js", "assets/.gitkeep", "nexo-preview.log", "New Text Document.txt"]) {
    fs.rmSync(path.join(stage, stale), { force: true });
}

const files = [];
function walk(directory) {
    for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
        const full = path.join(directory, entry.name);
        if (entry.isDirectory()) walk(full);
        else files.push({ path: path.relative(stage, full).replace(/\\/g, "/"), bytes: fs.statSync(full).size });
    }
}
walk(stage);
fs.writeFileSync(path.join(output, "manifest.json"), JSON.stringify({ version: "1.1.0", createdAt: new Date().toISOString(), files }, null, 2));

if (process.platform === "win32") {
    const archive = path.join(output, "NexoPlayer-source.zip");
    fs.rmSync(archive, { force: true });
    const result = spawnSync("tar", ["-a", "-cf", archive, "-C", stage, "."], { stdio: "inherit" });
    if (result.status !== 0) process.stderr.write("Could not create source ZIP; clean staging directory is still available.\n");
}

process.stdout.write(`Clean build staged at ${stage} (${files.length} files).\n`);
