#!/usr/bin/env node
import { createHash } from 'node:crypto'
import { spawnSync } from 'node:child_process'
import { copyFile, lstat, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'

const here = dirname(fileURLToPath(import.meta.url))
const platformRoot = resolve(here, '../..')
const workspaceRoot = resolve(platformRoot, '..')
const engineRoot = resolve(workspaceRoot, 'NODEDC_ENGINE_INFRA')
const artifactRoot = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || join(workspaceRoot, 'deploy-artifacts'))
const [patchId = '', ...extra] = process.argv.slice(2)

if (extra.length || !/^engine-restart-safe-auth-\d{8}-\d{3}$/.test(patchId)) {
  throw new Error('usage: build-engine-restart-safe-auth-artifact.mjs engine-restart-safe-auth-YYYYMMDD-NNN')
}

const entries = Object.freeze([
  'nodedc-source/server/auth/engineHandoffSession.js',
  'nodedc-source/server/index.js',
  'nodedc-source/src/App.tsx',
  'nodedc-source/src/platform/auth/access.ts',
  'nodedc-source/src/platform/auth/sessionRecovery.ts',
  'nodedc-source/dist/index.html',
  'nodedc-source/dist/assets/index-Bim2pv1P.css',
  'nodedc-source/dist/assets/index-4TenBzkg.js',
])

const candidateSha256 = Object.freeze({
  'nodedc-source/server/auth/engineHandoffSession.js': '0cc5bf02b11cd5fc8cc8cad018091ca93efb13bc72616348ada61105af15bd8e',
  'nodedc-source/server/index.js': '0ac408e0e9a7bc5c8e13a00afc957b982b065e2bc414919839e0b0a11aa05ba4',
  'nodedc-source/src/App.tsx': 'd9bc0f23ceaaf4f5534ac9a9b1f97d84fd8eee4679c59b5999b5a75b8c77bb32',
  'nodedc-source/src/platform/auth/access.ts': '9610dc1622a1c9b383eb3a1569347098002aa058dbbcbb23f096f2622d452222',
  'nodedc-source/src/platform/auth/sessionRecovery.ts': 'f931cbb45d64d5d6a2868194e8c73879a408dffca1fdd7e41acfa262441c50d7',
  'nodedc-source/dist/index.html': 'b031f6720683f6fb5ccfa59a01414ff2a3efcdf548b1c6aab33e1748ee3f003d',
  'nodedc-source/dist/assets/index-Bim2pv1P.css': '18322addd45c126a7b8396f36b005f3085fddba3e9b346dd2c910f6fa6987ebf',
  'nodedc-source/dist/assets/index-4TenBzkg.js': 'a48fcacf3348c20a432cd6da2627b89c0c3e54bc989c727b620125dd3412538a',
})

const predecessorSha256 = Object.freeze({
  'nodedc-source/server/index.js': 'b2b790b02839570d967a2ca68b00e2724485a99389ac9b3a589a1b22302a36b8',
  'nodedc-source/src/App.tsx': '2ea264a59c3e82f763be74f0312cb1aa6bce856644ba0bc7024d77e238e7eb41',
  'nodedc-source/src/platform/auth/access.ts': '4fb9c4d524765dff8a5360efa1c0acf1d203da1cc2c7fd3b98e1456261d43d41',
  'nodedc-source/src/platform/auth/sessionRecovery.ts': '997d3a18e439308d4650e3c7324710a8b17dea29976001c4275c84d96b18ccfe',
})

for (const [rel, expected] of Object.entries(predecessorSha256)) {
  const result = spawnSync('git', ['-C', engineRoot, 'show', `HEAD:${rel}`], {
    stdio: ['ignore', 'pipe', 'pipe'],
    maxBuffer: 128 * 1024 * 1024,
  })
  if (result.status !== 0 || digest(result.stdout) !== expected) {
    throw new Error(`engine_auth_predecessor_mismatch:${rel}`)
  }
}

const newModulePath = 'nodedc-source/server/auth/engineHandoffSession.js'
const newModuleProbe = spawnSync('git', ['-C', engineRoot, 'cat-file', '-e', `HEAD:${newModulePath}`], {
  stdio: 'ignore',
})
if (newModuleProbe.status === 0) throw new Error('engine_auth_new_module_predecessor_unexpected')

for (const rel of entries) {
  const source = resolve(engineRoot, rel)
  const info = await lstat(source)
  if (info.isSymbolicLink() || !info.isFile()) throw new Error(`engine_auth_candidate_unsafe:${rel}`)
  if (digest(await readFile(source)) !== candidateSha256[rel]) {
    throw new Error(`engine_auth_candidate_sha256_mismatch:${rel}`)
  }
}

const indexHtml = await readFile(resolve(engineRoot, 'nodedc-source/dist/index.html'), 'utf8')
if (!indexHtml.includes('/assets/index-4TenBzkg.js') || !indexHtml.includes('/assets/index-Bim2pv1P.css')) {
  throw new Error('engine_auth_dist_entrypoint_mismatch')
}

await mkdir(artifactRoot, { recursive: true })
const artifact = join(artifactRoot, `nodedc-${patchId}.tgz`)
await assertArtifactTargetFresh(artifact)
const stage = await mkdtemp(join(tmpdir(), 'nodedc-engine-restart-safe-auth-'))

try {
  await writeFile(
    join(stage, 'manifest.env'),
    `id=${patchId}\ncomponent=engine\ntype=app-overlay\n`,
    'utf8',
  )
  await writeFile(join(stage, 'files.txt'), `${entries.join('\n')}\n`, 'utf8')
  for (const rel of entries) {
    const target = join(stage, 'payload', rel)
    await mkdir(dirname(target), { recursive: true })
    await copyFile(resolve(engineRoot, rel), target)
  }
  run('python3', ['-c', canonicalTarScript(), artifact, stage])
  console.log(JSON.stringify({
    ok: true,
    patchId,
    artifact,
    sha256: digest(await readFile(artifact)),
    entries,
    predecessorSha256,
    candidateSha256,
    runtimeServices: ['nodedc-backend', 'app'],
  }, null, 2))
} finally {
  await rm(stage, { recursive: true, force: true })
}

async function assertArtifactTargetFresh(target) {
  try {
    await lstat(target)
  } catch (error) {
    if (error?.code === 'ENOENT') return
    throw error
  }
  throw new Error('engine_auth_artifact_already_exists')
}

function canonicalTarScript() {
  return [
    'import gzip,io,pathlib,sys,tarfile',
    'root=pathlib.Path(sys.argv[2])',
    "with open(sys.argv[1],'wb') as out:",
    "  with gzip.GzipFile(filename='',mode='wb',fileobj=out,compresslevel=9,mtime=0) as gz:",
    "    with tarfile.open(fileobj=gz,mode='w',format=tarfile.PAX_FORMAT) as tar:",
    "      for top in ('manifest.env','files.txt','payload'):",
    "        p=root/top; paths=[p]+(sorted(p.rglob('*')) if p.is_dir() else [])",
    '        for x in paths:',
    "          info=tar.gettarinfo(str(x),arcname=x.relative_to(root).as_posix())",
    "          info.uid=info.gid=0; info.uname=info.gname='root'; info.mtime=0; info.mode=0o755 if info.isdir() else 0o644",
    "          with (open(x,'rb') if info.isfile() else io.BytesIO()) as src: tar.addfile(info,src if info.isfile() else None)",
  ].join('\n')
}

function run(command, args) {
  const result = spawnSync(command, args, {
    encoding: 'utf8',
    stdio: ['ignore', 'pipe', 'pipe'],
    maxBuffer: 128 * 1024 * 1024,
  })
  if (result.status !== 0) throw new Error(`${command}_failed:${result.stderr || result.stdout}`)
}

function digest(bytes) {
  return createHash('sha256').update(bytes).digest('hex')
}
