import { ensureDir, type PackageJSON } from './util.ts';
import { readFile, writeFile } from './util.ts';
import { join } from 'node:path';

export async function readPackageJson(pkgJsonDir: string) {
  const pkgJsonPath = join(pkgJsonDir, 'package.json');
  const pkgJson: PackageJSON = JSON.parse(await readFile(pkgJsonPath, 'utf-8'));
  return pkgJson;
}

export async function writePackageJson(pkgJsonDir: string, pkgJson: PackageJSON) {
  ensureDir(pkgJsonDir);
  const pkgJsonPath = join(pkgJsonDir, 'package.json');
  const pkgJsonStr = JSON.stringify(pkgJson, null, 2) + '\n';
  await writeFile(pkgJsonPath, pkgJsonStr);
}

/** Write a private submodule package.json with standard fields. */
export async function writeSubmodulePackageJson(
  dir: string,
  name: string,
  version: string,
  overrides?: Partial<PackageJSON>
) {
  await writePackageJson(dir, {
    name,
    version,
    main: 'index.mjs',
    types: 'index.d.ts',
    private: true,
    type: 'module',
    ...overrides,
  });
}
