#!/usr/bin/env node
/**
 * sync-mac-binary.js — copy Mac binaries from the OneDrive-synced `mac/`
 * staging area into `msger-native/bin/` so they ship in the next npm publish.
 *
 * Workflow:
 *   - On a Mac: run `build-mac.sh`. It compiles, ad-hoc codesigns, and drops
 *     the binary into `mac/msgernative-darwin-{arm64,x64}`.
 *   - OneDrive syncs that file back to Windows.
 *   - This script (run by `prepublishOnly`) copies it into `msger-native/bin/`.
 *
 * Gated by `platforms.mac` in builder/build-config.json (parallel to `pi`).
 * Skipped entirely when false so a publish doesn't refresh Mac binaries — useful
 * when no Mac is available, or to avoid pulling in a stale OneDrive copy.
 *
 * Tolerant of a missing `mac/` or missing binaries — Mac is built rarely, and
 * a publish without a current Mac binary is fine. Mac users on that version
 * will get a clear "Binary not found" error and can flag it for a rebuild.
 */
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import JSON5 from "json5";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const macDir = path.join(__dirname, "mac");
const binDir = path.join(__dirname, "msger-native", "bin");
const configPath = path.join(__dirname, "msger-native", "builder", "build-config.json");

// build-config.json may contain comments — use json5 (already a msger dep).
const config = JSON5.parse(fs.readFileSync(configPath, "utf-8"));
if (!config.platforms?.mac) {
    console.log("  msger: platforms.mac=false in build-config.json — skipping Mac binary sync");
    process.exit(0);
}

const targets = ["msgernative-darwin-arm64", "msgernative-darwin-x64"];

if (!fs.existsSync(macDir)) {
    console.log("  msger: no mac/ staging dir — skipping Mac binary sync");
    process.exit(0);
}

let copied = 0;
let skipped = 0;
for (const name of targets) {
    const src = path.join(macDir, name);
    const dst = path.join(binDir, name);
    if (!fs.existsSync(src)) continue;

    const srcMtime = fs.statSync(src).mtimeMs;
    const dstMtime = fs.existsSync(dst) ? fs.statSync(dst).mtimeMs : 0;
    if (dstMtime >= srcMtime) {
        console.log(`  msger: ${name} already current in bin/`);
        skipped++;
        continue;
    }

    try {
        fs.copyFileSync(src, dst);
        fs.chmodSync(dst, 0o755);
        const sizeMB = (fs.statSync(dst).size / 1024 / 1024).toFixed(1);
        console.log(`  msger: synced ${name} (${sizeMB} MB) → bin/`);
        copied++;
    } catch (e) {
        console.error(`  msger: failed to sync ${name}: ${e.message}`);
        process.exit(1);
    }
}

if (copied === 0 && skipped === 0) {
    console.log("  msger: no Mac binaries in mac/ — Mac users will get \"Binary not found\" until you build one");
}
