import fs from 'node:fs';
import path from 'node:path';

export interface ComposerJson {
  name?: string;
  require?: Record<string, string>;
  'require-dev'?: Record<string, string>;
  scripts?: Record<string, string>;
}

export function readComposerJson(root: string): ComposerJson | null {
  const file = path.join(root, 'composer.json');
  if (!fs.existsSync(file)) return null;
  try {
    return JSON.parse(fs.readFileSync(file, 'utf8')) as ComposerJson;
  } catch {
    return null;
  }
}

export function hasComposerDependency(pkg: ComposerJson | null, name: string): boolean {
  if (!pkg) return false;
  return Boolean(pkg.require?.[name] || pkg['require-dev']?.[name]);
}

export function vendorBinExists(root: string, bin: string): boolean {
  const suffix = process.platform === 'win32' ? '.bat' : '';
  return fs.existsSync(path.join(root, 'vendor', 'bin', `${bin}${suffix}`)) || fs.existsSync(path.join(root, 'vendor', 'bin', bin));
}
