"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TRUSYS_BUNDLE_ZIP_NAME = exports.SESSION_DATA_DIR = void 0;
exports.encodeBootstrapPayload = encodeBootstrapPayload;
exports.buildPythonBootstrap = buildPythonBootstrap;
exports.buildJavaScriptBootstrap = buildJavaScriptBootstrap;
exports.buildBootstrapCode = buildBootstrapCode;
const parseProviderFilePath_1 = require("./parseProviderFilePath");
const parseExecutionResult_1 = require("./parseExecutionResult");
exports.SESSION_DATA_DIR = '/mnt/data';
exports.TRUSYS_BUNDLE_ZIP_NAME = 'trusys_bundle.zip';
/** Base64 JSON embedded in bootstrap — Node sessions may not see uploaded payload files before chdir. */
function encodeBootstrapPayload(payload) {
    return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64');
}
function buildPythonBootstrap(providerFilePath, payloadBase64) {
    const { fileName, functionName } = (0, parseProviderFilePath_1.parseProviderFilePath)('py', providerFilePath);
    return `
import base64
import importlib.util
import json
import os
import subprocess
import sys

os.chdir("${exports.SESSION_DATA_DIR}")

bundle_zip = os.path.join("${exports.SESSION_DATA_DIR}", "${exports.TRUSYS_BUNDLE_ZIP_NAME}")
if os.path.isfile(bundle_zip):
    import zipfile
    with zipfile.ZipFile(bundle_zip) as zf:
        zf.extractall("${exports.SESSION_DATA_DIR}")

payload = json.loads(base64.b64decode("${payloadBase64}").decode("utf-8"))

for key, value in (payload.get("env") or {}).items():
    os.environ[str(key)] = str(value)

if os.path.isfile(os.path.join("${exports.SESSION_DATA_DIR}", "requirements.txt")):
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", "-r", "requirements.txt", "-q"],
        cwd="${exports.SESSION_DATA_DIR}",
    )

provider_path = os.path.join("${exports.SESSION_DATA_DIR}", "${fileName}")
provider_dir = os.path.dirname(os.path.abspath(provider_path))
data_dir = os.path.abspath("${exports.SESSION_DATA_DIR}")
for path_entry in (data_dir, provider_dir):
    if path_entry and path_entry not in sys.path:
        sys.path.insert(0, path_entry)

spec = importlib.util.spec_from_file_location("trusys_user_provider", provider_path)
if spec is None or spec.loader is None:
    raise RuntimeError(f"Failed to load provider module from {provider_path}")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

fn = getattr(module, "${functionName}", None)
if fn is None or not callable(fn):
    raise AttributeError("Callable ${functionName} not found in ${fileName}")

prompt = payload.get("prompt", "")
context = payload.get("context") or {}
result = fn(prompt, context)
if not isinstance(result, dict):
    raise TypeError("call_api must return a dict")

print("${parseExecutionResult_1.TRUSYS_RESULT_PREFIX}" + json.dumps(result))
`.trim();
}
function buildJavaScriptBootstrap(providerFilePath, payloadBase64, options) {
    const { fileName, functionName } = (0, parseProviderFilePath_1.parseProviderFilePath)('js', providerFilePath);
    const dataDir = exports.SESSION_DATA_DIR;
    return `
    (function () {

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

const dataDir = '${dataDir}';
process.chdir(dataDir);

const bundleZip = path.join(dataDir, '${exports.TRUSYS_BUNDLE_ZIP_NAME}');

if (fs.existsSync(bundleZip)) {
  const extractScript =
    "import zipfile, sys; zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])";

  try {
    execSync(
      \`python3 -c "\${extractScript}" "\${bundleZip}" "\${dataDir}"\`,
      {
        cwd: dataDir,
        stdio: 'pipe',
        timeout: 30000,
      }
    );
  } catch (err) {
    console.error('python unzip failed', err?.message || err);

    execSync(
      \`unzip -o -q "\${bundleZip}" -d "\${dataDir}"\`,
      {
        cwd: dataDir,
        stdio: 'pipe',
        timeout: 30000,
      }
    );
  }
}

const payload = JSON.parse(
  Buffer.from('${payloadBase64}', 'base64').toString('utf8')
);

for (const [key, value] of Object.entries(payload.env || {})) {
  process.env[String(key)] = String(value);
}

try {
  const providerPath = path.join(dataDir, '${fileName}');

  const providerModule = require(providerPath);

  const fn =
    providerModule?.${functionName} ??
    providerModule?.default?.${functionName} ??
    (typeof providerModule === 'function' ? providerModule : null);

  if (typeof fn !== 'function') {
    throw new Error('Callable ${functionName} not found');
  }

  const result = fn(payload.prompt ?? '', payload.context ?? {});

  console.log(
    '${parseExecutionResult_1.TRUSYS_RESULT_PREFIX}' +
    JSON.stringify(result)
  );
} catch (err) {
  console.error(err?.stack || String(err));
  process.exit(1);
}
})();
`.trim();
}
function buildBootstrapCode(language, providerFilePath, payload, options) {
    const payloadBase64 = encodeBootstrapPayload(payload);
    return language === 'py'
        ? buildPythonBootstrap(providerFilePath, payloadBase64)
        : buildJavaScriptBootstrap(providerFilePath, payloadBase64, options);
}
//# sourceMappingURL=buildBootstrap.js.map