#!/usr/bin/env bash
# Install a Teletraan module.  Usage: add-module.sh <module-name>
set -euo pipefail

MODULE="${1:-}"
if [ -z "$MODULE" ]; then
  echo "Usage: $0 <module-name>" >&2
  exit 1
fi

DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FRAMEWORK_ROOT="$(dirname "$DIR")"
CONFIG="$FRAMEWORK_ROOT/config/system.json"

if [ ! -f "$CONFIG" ]; then
  echo "Error: system.json not found at $CONFIG" >&2
  echo "Run the main installer first." >&2
  exit 1
fi

if [ ! -d "$FRAMEWORK_ROOT/modules/$MODULE" ]; then
  echo "Error: module '$MODULE' not found in $FRAMEWORK_ROOT/modules/" >&2
  echo "Available modules:" >&2
  ls "$FRAMEWORK_ROOT/modules/" >&2
  exit 1
fi

node --input-type=module <<EOF
import { installModule } from '$FRAMEWORK_ROOT/installer/modules.js';
import { setup } from '$FRAMEWORK_ROOT/modules/$MODULE/setup.js';
import { readFileSync } from 'node:fs';
import readline from 'node:readline';

const systemConfig = JSON.parse(readFileSync('$CONFIG', 'utf8'));

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: true,
});

let userConfig;
try {
  userConfig = await setup(systemConfig, rl);
} finally {
  rl.close();
}

const result = installModule('$MODULE', systemConfig, userConfig);
console.log('\\nDone. Module installed to:', result.installPath);
EOF
