import { execFileSync } from 'node:child_process'
import { mkdir, stat } from 'node:fs/promises'
import { dirname, resolve } from 'node:path'
import { readFile } from 'node:fs/promises'

const root = resolve(new URL('..', import.meta.url).pathname)
const toolchain = JSON.parse(await readFile(new URL('../config/freecad-toolchain.json', import.meta.url), 'utf8'))
const directoryArgument = process.argv.slice(2).find((argument) => argument.startsWith('--directory='))
const target = resolve(root, directoryArgument?.slice('--directory='.length) || toolchain.sourceCheckout.defaultDirectory)
const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'], timeout: 300000 }).trim()
const exists = await stat(target).then(() => true, () => false)

if (!exists) {
  await mkdir(dirname(target), { recursive: true })
  git('clone', '--filter=blob:none', '--no-checkout', toolchain.source.repository, target)
} else {
  const remote = git('-C', target, 'remote', 'get-url', 'origin')
  if (remote !== toolchain.source.repository) throw new Error(`Existing checkout has unexpected origin: ${remote}`)
  const dirty = git('-C', target, 'status', '--porcelain')
  if (dirty) throw new Error(`Existing FreeCAD checkout is dirty: ${target}`)
}

git('-C', target, 'fetch', '--depth=1', 'origin', `refs/tags/${toolchain.source.tag}`)
const fetched = git('-C', target, 'rev-parse', 'FETCH_HEAD')
if (fetched !== toolchain.source.commit) throw new Error(`Fetched FreeCAD tag resolved to ${fetched}, expected ${toolchain.source.commit}.`)
git('-C', target, 'checkout', '--detach', toolchain.source.commit)
// The locked source graph includes GSL, OndselSolver, AddonManager and the
// test support checkout. Initialize every gitlink so a clean oracle build does
// not silently fall back to a partial module set.
git('-C', target, 'submodule', 'sync', '--recursive')
git('-C', target, 'submodule', 'update', '--init', '--recursive')
console.log(`FreeCAD source ready: ${target} @ ${toolchain.source.commit}`)
