import { readdir } from "node:fs/promises"
import { join } from "node:path"

export type PackageInfo = {
  path: string
  json: {
    name: string
    version: string
    scripts?: Record<string, string>
    dependencies?: Record<string, string>
    devDependencies?: Record<string, string>
    prettier?: Record<string, string>
  }
}

export const getPackageInfo = async (): Promise<PackageInfo[]> => {
  const packagesDir = join(import.meta.dir, "../../")
  const packageNames = await readdir(packagesDir)

  const packageInfo: PackageInfo[] = []
  for (const packageName of packageNames) {
    const path = join(packagesDir, packageName)
    try {
      const dir = await Bun.file(path)
      const stats = await dir.stat()
      if (!stats.isDirectory()) {
        continue
      }

      const jsonPath = join(path, "package.json")
      const json = await Bun.file(jsonPath).json()

      packageInfo.push({ path, json })
    } catch (error) {
      console.error(`Error processing package ${packageName}:`, error)
    }
  }

  return packageInfo
}
