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

const repoRoot = path.resolve(__dirname, '..');
const commonPlatRoot =
  process.env.BYTELYST_COMMON_PLAT_ROOT ||
  path.resolve(repoRoot, '..', 'learning_ai_common_plat');
const commonPackagesRoot = path.join(commonPlatRoot, 'packages');

const manifests = [
  path.join(repoRoot, 'package.json'),
  path.join(repoRoot, 'web', 'package.json'),
  path.join(repoRoot, 'backend', 'package.json'),
  path.join(repoRoot, 'mobile', 'package.json'),
];

function readJson(filePath) {
  return JSON.parse(fs.readFileSync(filePath, 'utf8'));
}

function bytelystDependencies(manifestPath) {
  const manifest = readJson(manifestPath);
  const sections = [
    manifest.dependencies,
    manifest.devDependencies,
    manifest.optionalDependencies,
  ];

  return sections
    .flatMap((section) => Object.keys(section || {}))
    .filter((name) => name.startsWith('@bytelyst/'));
}

if (!fs.existsSync(commonPackagesRoot)) {
  console.error(`Missing common platform packages directory: ${commonPackagesRoot}`);
  console.error('Set BYTELYST_COMMON_PLAT_ROOT if your sibling checkout lives elsewhere.');
  process.exit(1);
}

const missing = new Set();

for (const manifestPath of manifests) {
  if (!fs.existsSync(manifestPath)) continue;

  for (const packageName of bytelystDependencies(manifestPath)) {
    const packageDir = packageName.replace('@bytelyst/', '');
    const packageJsonPath = path.join(commonPackagesRoot, packageDir, 'package.json');
    if (!fs.existsSync(packageJsonPath)) {
      missing.add(`${packageName} -> ${packageJsonPath}`);
    }
  }
}

if (missing.size > 0) {
  console.error('Missing local ByteLyst package checkouts:');
  for (const item of missing) {
    console.error(`- ${item}`);
  }
  process.exit(1);
}

console.log(`Local ByteLyst packages resolved from ${commonPackagesRoot}`);
