const fs = require('node:fs');
const path = require('node:path');

const PACKAGE_SCOPE = '@bytelyst/';
const PACKAGE_SOURCE = process.env.BYTELYST_PACKAGE_SOURCE || 'common-plat';
const COMMON_PLAT_ROOT = process.env.BYTELYST_COMMON_PLAT_ROOT || path.resolve(__dirname, '../../..');
const COMMON_PLAT_PACKAGES_ROOT = path.join(COMMON_PLAT_ROOT, 'packages');
const VERSION_CACHE = new Map();
let loggedSource = false;

function packageDirFor(name) {
  return name.startsWith(PACKAGE_SCOPE) ? name.slice(PACKAGE_SCOPE.length) : null;
}

function pathIfPackageExists(rootDir, name) {
  const packageDir = packageDirFor(name);
  if (!packageDir) return null;

  const candidate = path.join(rootDir, packageDir);
  return fs.existsSync(path.join(candidate, 'package.json')) ? candidate : null;
}

function readPackageVersion(packagePath) {
  if (VERSION_CACHE.has(packagePath)) {
    return VERSION_CACHE.get(packagePath);
  }

  try {
    const packageJson = JSON.parse(fs.readFileSync(path.join(packagePath, 'package.json'), 'utf8'));
    const version = packageJson.version || null;
    VERSION_CACHE.set(packagePath, version);
    return version;
  } catch {
    VERSION_CACHE.set(packagePath, null);
    return null;
  }
}

function resolveSpecifier(name) {
  if (!name.startsWith(PACKAGE_SCOPE)) {
    return null;
  }

  const commonPlatPath = pathIfPackageExists(COMMON_PLAT_PACKAGES_ROOT, name);

  if (PACKAGE_SOURCE === 'common-plat') {
    return commonPlatPath ? 'workspace:*' : null;
  }

  if (PACKAGE_SOURCE === 'gitea') {
    return commonPlatPath ? readPackageVersion(commonPlatPath) : null;
  }

  return commonPlatPath ? 'workspace:*' : null;
}

function rewriteDependencySet(dependencies = {}) {
  for (const dependencyName of Object.keys(dependencies)) {
    const rewrittenSpecifier = resolveSpecifier(dependencyName);
    if (rewrittenSpecifier) {
      dependencies[dependencyName] = rewrittenSpecifier;
    }
  }
}

function logSourceOnce() {
  if (loggedSource) {
    return;
  }

  loggedSource = true;
  process.stderr.write(
    `[bytelyst] pnpm package source=${PACKAGE_SOURCE} commonPlatRoot=${COMMON_PLAT_ROOT}\n`,
  );
}

module.exports = {
  hooks: {
    readPackage(packageJson) {
      logSourceOnce();
      if (packageJson.name?.startsWith(PACKAGE_SCOPE)) {
        return packageJson;
      }

      rewriteDependencySet(packageJson.dependencies);
      rewriteDependencySet(packageJson.devDependencies);
      rewriteDependencySet(packageJson.optionalDependencies);
      return packageJson;
    },
  },
};