#!/usr/bin/env node
const fs = require('fs');
const path = require('path');

const projectRoot = path.resolve(__dirname, '..');

function resolveMonacoPackageJson() {
  try {
    const resolvedPath = require.resolve('monaco-editor/package.json', {
      paths: [projectRoot],
    });
    return resolvedPath;
  } catch (error) {
    console.error('[dees-workspace] Unable to resolve monaco-editor/package.json');
    throw error;
  }
}

function getMonacoVersion() {
  const monacoPackagePath = resolveMonacoPackageJson();
  const monacoPackage = require(monacoPackagePath);
  if (!monacoPackage.version) {
    throw new Error('[dees-workspace] monaco-editor/package.json does not expose a version field');
  }
  return monacoPackage.version;
}

function writeVersionModule(version) {
  const targetDir = path.join(projectRoot, 'ts_web', 'elements', '00group-workspace', 'dees-workspace-monaco');
  fs.mkdirSync(targetDir, { recursive: true });
  const targetFile = path.join(targetDir, 'version.ts');
  const fileContent = `// Auto-generated by scripts/update-monaco-version.cjs\nexport const MONACO_VERSION = '${version}';\n`;
  fs.writeFileSync(targetFile, fileContent, 'utf8');
  console.log(`[dees-workspace] Wrote ${path.relative(projectRoot, targetFile)} with monaco-editor@${version}`);
}

try {
  const version = getMonacoVersion();
  writeVersionModule(version);
} catch (error) {
  console.error('[dees-workspace] Failed to update Monaco version module.');
  console.error(error instanceof Error ? error.message : error);
  process.exitCode = 1;
}
