/**
 * Postinstall script: ensures the `openclaw` shim package is available
 * in node_modules so that `@tencent-weixin/openclaw-weixin` can resolve
 * `openclaw/plugin-sdk` imports at runtime.
 *
 * In local development, pnpm workspaces + overrides handle this.
 * After `npm install` from the registry, this script copies the shim
 * from the bundled `packages/openclaw-sdk-shim/` into node_modules.
 */

import { existsSync, mkdirSync, cpSync, realpathSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";

const __dirname = dirname(fileURLToPath(import.meta.url));
const root = join(__dirname, "..");
const shimSrc = join(root, "packages", "openclaw-sdk-shim");
const shimDest = join(root, "node_modules", "openclaw");

// Skip if shim source doesn't exist
if (!existsSync(shimSrc)) {
  process.exit(0);
}

// In workspace installs, pnpm may already point `node_modules/openclaw`
// at this exact shim directory. Copying a directory onto itself crashes.
if (existsSync(shimDest)) {
  try {
    if (realpathSync(shimSrc) === realpathSync(shimDest)) {
      process.exit(0);
    }
  } catch {
    // Fall through and attempt to copy below.
  }
}

// Otherwise copy (overwrite) to keep the published shim in sync with source.
mkdirSync(dirname(shimDest), { recursive: true });
cpSync(shimSrc, shimDest, { recursive: true, force: true });
