#!/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 predecessorArtifact = resolve(
  process.env.NODEDC_ENGINE_AUTH_RECOVERY_PREDECESSOR
    || '/Volumes/docker/nodedc-deploy/applied/nodedc-engine-restart-safe-auth-20260719-001.tgz',
)
const [patchId = '', ...extra] = process.argv.slice(2)

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

const predecessorArtifactSha256 = 'f6830046d7bd2bc32c1dbda8dce7ddf68d15c1e728f594c0f64ee8feec3911b8'
const predecessorManifest = 'id=engine-restart-safe-auth-20260719-001\ncomponent=engine\ntype=app-overlay\n'
const predecessorSha256 = Object.freeze({
  'nodedc-source/src/platform/auth/access.ts': '9610dc1622a1c9b383eb3a1569347098002aa058dbbcbb23f096f2622d452222',
  'nodedc-source/src/platform/auth/sessionRecovery.ts': 'f931cbb45d64d5d6a2868194e8c73879a408dffca1fdd7e41acfa262441c50d7',
  'nodedc-source/dist/index.html': 'b031f6720683f6fb5ccfa59a01414ff2a3efcdf548b1c6aab33e1748ee3f003d',
})
const entries = Object.freeze([
  'nodedc-source/src/platform/auth/access.ts',
  'nodedc-source/src/platform/auth/sessionRecovery.ts',
  'nodedc-source/dist/index.html',
  'nodedc-source/dist/assets/index-DJ1CMfu4.js',
])
const candidateSha256 = Object.freeze({
  'nodedc-source/src/platform/auth/access.ts': 'c686db2568912a093ea8934e34889254ddd659594f7084025c280732ef627002',
  'nodedc-source/src/platform/auth/sessionRecovery.ts': '63f3e2379628dea3b119c4283bc0c3bb10e94199c673b9d9c579bac3c54be98f',
  'nodedc-source/dist/index.html': '8894f62ad590168862e81266bc4602410279634b666af72cb14ad80aeb71ea74',
  'nodedc-source/dist/assets/index-DJ1CMfu4.js': 'a0aaf72d2ed390142ff2ea03dbcfdd534637e5faefd80d8aa7d705a804abe065',
})

const predecessorInfo = await lstat(predecessorArtifact)
if (predecessorInfo.isSymbolicLink() || !predecessorInfo.isFile()) {
  throw new Error('engine_auth_recovery_predecessor_unsafe')
}
if (digest(await readFile(predecessorArtifact)) !== predecessorArtifactSha256) {
  throw new Error('engine_auth_recovery_predecessor_archive_mismatch')
}
run('python3', [
  '-c', verifyPredecessorScript(), predecessorArtifact,
  predecessorArtifactSha256, predecessorManifest, JSON.stringify(predecessorSha256),
])

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_recovery_candidate_unsafe:${rel}`)
  if (digest(await readFile(source)) !== candidateSha256[rel]) {
    throw new Error(`engine_auth_recovery_candidate_sha256_mismatch:${rel}`)
  }
}
const indexHtml = await readFile(resolve(engineRoot, 'nodedc-source/dist/index.html'), 'utf8')
if (!indexHtml.includes('/assets/index-DJ1CMfu4.js') || !indexHtml.includes('/assets/index-Bim2pv1P.css')) {
  throw new Error('engine_auth_recovery_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-auth-redirect-recovery-'))

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)),
    predecessorArtifact,
    predecessorArtifactSha256,
    predecessorSha256,
    candidateSha256,
    entries,
    runtimeServices: ['nodedc-backend', 'app'],
  }, null, 2))
} finally {
  await rm(stage, { recursive: true, force: true })
}

function verifyPredecessorScript() {
  return [
    'import hashlib,json,pathlib,sys,tarfile',
    'source=pathlib.Path(sys.argv[1]); expected_archive=sys.argv[2]',
    'expected_manifest=sys.argv[3].encode(); hashes=json.loads(sys.argv[4])',
    "assert hashlib.sha256(source.read_bytes()).hexdigest()==expected_archive, 'archive-sha256'",
    "with tarfile.open(source,'r:gz') as tar:",
    "  assert tar.extractfile('manifest.env').read()==expected_manifest, 'manifest'",
    '  for rel,wanted in hashes.items():',
    "    data=tar.extractfile('payload/'+rel).read()",
    "    assert hashlib.sha256(data).hexdigest()==wanted, 'payload:'+rel",
  ].join('\n')
}

async function assertArtifactTargetFresh(target) {
  try {
    await lstat(target)
  } catch (error) {
    if (error?.code === 'ENOENT') return
    throw error
  }
  throw new Error('engine_auth_recovery_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')
}
