#!/usr/bin/env node
/**
 * Post-install: install Gateway dependencies so "npm start" in apps/gateway works.
 * The published package copies gateway source+dist but not node_modules; install them here.
 */

import { execSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const gatewayDir = path.join(__dirname, '..', 'apps', 'gateway');
const packageJson = path.join(gatewayDir, 'package.json');
const nodeModules = path.join(gatewayDir, 'node_modules');

if (!fs.existsSync(packageJson)) {
  process.exit(0); // No gateway in this install
}

const prismaSchema = path.join(__dirname, '..', 'prisma', 'schema.prisma');

function ensurePrismaClient() {
  if (!fs.existsSync(prismaSchema)) {
    return;
  }
  try {
    console.log('🔧 Prisma: generating client for Gateway (global 4runr-os install)...');
    execSync('npm run db:generate', {
      cwd: gatewayDir,
      stdio: 'inherit',
      shell: process.platform === 'win32',
    });
    console.log('✓ Prisma client ready for Gateway');
  } catch (err) {
    console.warn(
      '⚠️  prisma generate failed. OS auto-start Gateway may fail until you run:\n' +
        '  cd apps/gateway && npm run db:generate',
    );
  }
}

if (fs.existsSync(nodeModules) && fs.readdirSync(nodeModules).length > 0) {
  ensurePrismaClient();
  process.exit(0); // Deps already present (e.g. from prepublish) — still (re)generate Prisma
}

try {
  console.log('📦 Installing Gateway dependencies (one-time)...');
  execSync('npm install --omit=dev', {
    cwd: gatewayDir,
    stdio: 'inherit',
    shell: process.platform === 'win32',
  });
  console.log('✓ Gateway dependencies ready');
} catch (err) {
  console.warn('⚠️  Gateway dependency install failed. Start gateway from repo with: cd apps/gateway && npm start');
  // Don't fail the main install
}

ensurePrismaClient();
