import { execFileSync } from 'node:child_process'
import { readFile } from 'node:fs/promises'
import { resolve } from 'node:path'

const toolchain = JSON.parse(await readFile(new URL('../config/freecad-toolchain.json', import.meta.url), 'utf8'))
const reference = `refs/tags/${toolchain.source.tag}`
const root = resolve(new URL('..', import.meta.url).pathname)
const source = resolve(root, toolchain.sourceCheckout.defaultDirectory)
const git = (...args) => execFileSync('git', args, { encoding: 'utf8', timeout: 30000 }).trim()

if (process.env.FREECAD_SOURCE_OFFLINE === '1') {
  const revision = git('-C', source, 'rev-parse', 'HEAD')
  if (revision !== toolchain.source.commit) {
    console.error(`FreeCAD source mismatch: expected ${toolchain.source.commit}, received ${revision}.`)
    process.exit(1)
  }
  const submodules = git('-C', source, 'submodule', 'status', '--recursive').split(/\r?\n/).filter(Boolean)
  const incomplete = submodules.filter((line) => line.startsWith('-') || line.startsWith('+') || line.startsWith('U'))
  if (submodules.length !== 4 || incomplete.length > 0) {
    console.error(`FreeCAD offline source requires four clean initialized submodules; received ${JSON.stringify(submodules)}.`)
    process.exit(1)
  }
  console.log(`FreeCAD offline source verified: ${source} @ ${revision}, submodules=${submodules.length}.`)
  process.exit(0)
}

const output = execFileSync('git', ['ls-remote', toolchain.source.repository, reference], { encoding: 'utf8', timeout: 30000 }).trim()
const [resolved, resolvedReference] = output.split(/\s+/)
if (resolvedReference !== reference || resolved !== toolchain.source.commit) {
  console.error(`FreeCAD tag mismatch: expected ${reference} @ ${toolchain.source.commit}, received ${output || 'no result'}.`)
  process.exit(1)
}
console.log(`FreeCAD source tag verified: ${reference} @ ${resolved}.`)
