import { buildPkg } from '../scripts/dist/pkg/build.js'
import { readMonorepo, traverseMonorepo } from '../scripts/dist/utils/monorepo-struct.js'
import { mkdir, readFile, rm, symlink, writeFile } from 'fs/promises'
import { dirname, join } from 'path'

const monorepoDir = process.cwd()
const monorepoStruct = await readMonorepo(monorepoDir)

for (const pkgJson of Object.values(monorepoStruct.pkgDirToJson)) {
  delete pkgJson.devDependencies?.['@fullcalendar-scripts/standard']

  if (pkgJson.tsConfig) {
    pkgJson.tsConfig.compilerOptions = {
      ...pkgJson.tsConfig.compilerOptions,
      module: 'Node16',
      ignoreDeprecations: '5.0',
      noEmitOnError: false,
      skipLibCheck: true,
    }
  }
}

await traverseMonorepo(monorepoStruct, async ({ pkgDir, pkgJson }) => {
  if (pkgJson.private || pkgDir.endsWith('/tests')) {
    return
  }

  await buildPkg(pkgDir, monorepoStruct, false)
  await rewriteLuxonEsmImport(pkgJson.name, pkgDir)
  await linkDistPackage(pkgJson.name, pkgDir)
})

async function rewriteLuxonEsmImport(pkgName, pkgDir) {
  if (!['@fullcalendar/luxon', '@fullcalendar/luxon2', '@fullcalendar/luxon3'].includes(pkgName)) {
    return
  }

  const filePath = join(pkgDir, 'dist', 'index.js')
  const code = await readFile(filePath, 'utf8')

  await writeFile(
    filePath,
    code.replace(/ from 'luxon'/g, " from '/usr/share/nodejs/luxon/build/node/luxon.js'"),
  )
}

async function linkDistPackage(pkgName, pkgDir) {
  if (!pkgName.startsWith('@fullcalendar/')) {
    return
  }

  const linkPath = join(monorepoDir, 'node_modules', ...pkgName.split('/'))

  await mkdir(dirname(linkPath), { recursive: true })
  await rm(linkPath, { force: true, recursive: true })
  await symlink(join(pkgDir, 'dist'), linkPath, 'dir')
}
