#!/usr/bin/env node
/**
 * Post-install script: creates symlinks for workspace packages
 * so they resolve as @bobfrankston/mailx-* in node_modules.
 */

import fs from "node:fs";
import path from "node:path";

const root = path.resolve(import.meta.dirname, "..");
const packagesDir = path.join(root, "packages");
const nmDir = path.join(root, "node_modules", "@bobfrankston");

if (!fs.existsSync(packagesDir)) process.exit(0); // not in workspace layout

fs.mkdirSync(nmDir, { recursive: true });

for (const dir of fs.readdirSync(packagesDir)) {
    const pkgPath = path.join(packagesDir, dir, "package.json");
    if (!fs.existsSync(pkgPath)) continue;

    const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
    const name = pkg.name?.split("/")[1]; // e.g., "mailx-store" from "@bobfrankston/mailx-store"
    if (!name) continue;

    const linkPath = path.join(nmDir, name);
    const targetPath = path.join(packagesDir, dir);

    if (fs.existsSync(linkPath)) continue; // already linked

    try {
        // Use junction on Windows (no admin needed), symlink on Unix
        if (process.platform === "win32") {
            fs.symlinkSync(targetPath, linkPath, "junction");
        } else {
            fs.symlinkSync(targetPath, linkPath, "dir");
        }
    } catch (e: any) {
        console.error(`Failed to link ${name}: ${e.message}`);
    }
}
