import * as fs from 'node:fs';
import * as path from 'node:path';
import {
  packageNameToPath,
  readManifestFromPackageDir,
  resolvePackagesNodeModulesRoot,
} from '../utils/package-store.js';

export interface IInfoCommandOptions {
  readonly cwd?: string;
  readonly packagesDir?: string;
}

export interface IInfoCommandResult {
  readonly packageName: string;
  readonly installPath: string;
  readonly hasMatrixJson: boolean;
  readonly manifest: Record<string, unknown>;
}

export async function infoCommand(packageName: string, options: IInfoCommandOptions = {}): Promise<IInfoCommandResult> {
  const cwd = path.resolve(options.cwd ?? process.cwd());
  const nodeModulesRoot = resolvePackagesNodeModulesRoot(cwd, options.packagesDir);
  const installPath = path.join(nodeModulesRoot, packageNameToPath(packageName));
  if (!fs.existsSync(installPath)) {
    throw new Error(`Package is not installed: ${packageName}`);
  }

  const { packageName: resolvedName, manifest } = readManifestFromPackageDir(installPath);
  const hasMatrixJson = fs.existsSync(path.join(installPath, 'matrix.json'));

  return {
    packageName: resolvedName,
    installPath,
    hasMatrixJson,
    manifest,
  };
}
