#!/usr/bin/env node

/**
 * Postinstall script — create @vsaf/core workspace link
 *
 * Monorepo workspace links are stripped during `npm pack` (prepack removes
 * "workspaces" from package.json). This script recreates the link so that
 * `require('@vsaf/core')` works after `npm install -g`.
 *
 * Strategy (in order):
 *   1. symlink (macOS/Linux) or junction (Windows — no admin needed)
 *   2. cpSync fallback (copy dist/ contents)
 *   3. Fail with clear instructions
 */

const fs = require('fs');
const path = require('path');

const cwd = process.cwd();
const nsDir = path.resolve(cwd, 'node_modules', '@vsaf');
const target = path.resolve(nsDir, 'core');
const source = path.resolve(cwd, 'packages', 'core', 'dist');

// Skip if source doesn't exist (e.g. fresh clone before build)
if (!fs.existsSync(source)) {
  process.exit(0);
}

// Ensure @vsaf/ namespace directory
fs.mkdirSync(nsDir, { recursive: true });

// Clean existing link/dir
try { fs.rmSync(target, { recursive: true, force: true }); } catch {}

// Attempt 1: symlink (dir on Unix, junction on Windows)
try {
  const type = process.platform === 'win32' ? 'junction' : 'dir';
  fs.symlinkSync(source, target, type);
  process.exit(0);
} catch (e1) {
  // Attempt 2: copy
  try {
    fs.cpSync(source, target, { recursive: true });
    process.exit(0);
  } catch (e2) {
    // Both failed — show clear instructions
    console.error('\n' + '='.repeat(60));
    console.error('  VSAF postinstall failed: cannot link @vsaf/core');
    console.error('='.repeat(60));
    console.error(`\n  Symlink error: ${e1.message}`);
    console.error(`  Copy error:    ${e2.message}`);

    if (process.platform === 'win32') {
      console.error('\n  Windows fix (choose one):');
      console.error('  1. Enable Developer Mode:');
      console.error('     Settings > Update & Security > For Developers > Developer Mode ON');
      console.error('     Then re-run: npm install -g @ngocsangairvds/vsaf');
      console.error('');
      console.error('  2. Run as Administrator:');
      console.error('     Right-click terminal > "Run as administrator"');
      console.error('     Then re-run: npm install -g @ngocsangairvds/vsaf');
      console.error('');
      console.error('  3. Manual copy:');
      console.error(`     xcopy /E /I "${source}" "${target}"`);
    } else {
      console.error('\n  Fix: check file permissions on node_modules/');
      console.error(`  Manual: cp -r "${source}" "${target}"`);
    }

    console.error('\n' + '='.repeat(60) + '\n');
    process.exit(1);
  }
}
