#!/usr/bin/env node
/**
 * prep-mac-source.js — copy `msger-native/` Rust source into `mac/msger-native/`
 * so the Mac (which sees `mac/` via OneDrive) has source to build from.
 *
 * Run from Windows whenever the Rust source changes and you want the Mac to
 * pick it up on its next `./build-mac.sh`. Idempotent — only copies files that
 * are missing or newer.
 *
 * Excludes `target/` (build output, gigabytes), `pibuild/` (Pi-specific),
 * and the existing `bin/` (Linux/Windows binaries — Mac doesn't need them).
 */
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const srcDir = path.join(__dirname, "msger-native");
const dstDir = path.join(__dirname, "mac", "msger-native");

const SKIP_DIRS = new Set(["target", "pibuild", "bin", "node_modules", ".git"]);

if (!fs.existsSync(srcDir)) {
    console.error(`✗ msger-native/ not found at ${srcDir}`);
    process.exit(1);
}
if (!fs.existsSync(path.dirname(dstDir))) {
    console.error(`✗ mac/ not found — make sure the OneDrive junction is in place`);
    process.exit(1);
}

let copied = 0;
let skipped = 0;

function copyDir(src, dst) {
    fs.mkdirSync(dst, { recursive: true });
    for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
        const srcPath = path.join(src, entry.name);
        const dstPath = path.join(dst, entry.name);
        if (entry.isDirectory()) {
            if (SKIP_DIRS.has(entry.name)) continue;
            copyDir(srcPath, dstPath);
        } else if (entry.isFile()) {
            const srcMtime = fs.statSync(srcPath).mtimeMs;
            const dstMtime = fs.existsSync(dstPath) ? fs.statSync(dstPath).mtimeMs : 0;
            if (dstMtime >= srcMtime) {
                skipped++;
                continue;
            }
            fs.copyFileSync(srcPath, dstPath);
            copied++;
        }
    }
}

copyDir(srcDir, dstDir);

console.log(`  msger: prep:mac — ${copied} file(s) copied, ${skipped} unchanged`);
console.log(`  msger: source staged at mac/msger-native/. OneDrive will sync to the Mac;`);
console.log(`  msger: then run \`./build-mac.sh\` from the OneDrive folder on the Mac.`);
