#!/usr/bin/env node
/**
 * Create node_modules/@emoney symlink so Hardhat can resolve @emoney/* imports
 * (Foundry uses remappings in foundry.toml; Hardhat resolves from node_modules.)
 * Run automatically via "pnpm install" / "prepare" script.
 */
const fs = require('fs');
const path = require('path');

const root = path.resolve(__dirname, '..');
const nodeModules = path.join(root, 'node_modules');
const emoneyDir = path.join(nodeModules, '@emoney');
const target = path.join(root, 'contracts', 'emoney');

if (!fs.existsSync(path.join(root, 'contracts', 'emoney'))) {
  process.exit(0); // no contracts/emoney, skip
}

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

try {
  const stat = fs.lstatSync(emoneyDir);
  if (stat.isSymbolicLink()) {
    const current = fs.readlinkSync(emoneyDir);
    if (path.resolve(current) === path.resolve(target)) process.exit(0);
    fs.unlinkSync(emoneyDir);
  } else if (stat.isDirectory()) {
    // leave existing real @emoney package alone
    process.exit(0);
  }
} catch (e) {
  if (e.code !== 'ENOENT') throw e;
}

try {
  fs.symlinkSync(target, emoneyDir, 'dir');
} catch (e) {
  if (process.platform === 'win32') {
    try {
      fs.symlinkSync(target, emoneyDir, 'junction');
    } catch (e2) {
      console.warn('Could not create @emoney symlink:', e2.message);
    }
  } else {
    console.warn('Could not create @emoney symlink:', e.message);
  }
}
