#!/usr/bin/env node
import { createHash } from 'node:crypto'
import { spawnSync } from 'node:child_process'
import { cp, 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 engineRoot = resolve(
  process.env.NODEDC_ENGINE_SOURCE_ROOT || resolve(platformRoot, '../NODEDC_ENGINE_INFRA'),
)
const canonicalArtifactRoot = resolve(here, '../deploy-artifacts')
const artifactRoot = resolve(process.env.NODEDC_DEPLOY_ARTIFACT_DIR || canonicalArtifactRoot)
const [transitionId = '20260720-004', ...extra] = process.argv.slice(2)
if (extra.length || !/^\d{8}-[0-9]{3}$/.test(transitionId)) {
  throw new Error('usage: build-engine-mcp-autonomy-provider-v5-artifact.mjs [YYYYMMDD-NNN]')
}

const id = `engine-mcp-autonomy-provider-v5-${transitionId}`
const target = join(artifactRoot, `nodedc-${id}.tgz`)
const predecessorArtifact = join(
  canonicalArtifactRoot,
  'nodedc-engine-mcp-control-plane-20260718-003.tgz',
)
const predecessorArtifactSha256 = '249aef9527666c562e9648b15737e66cc5c1dc7c0788b58ea714da270b5eb4ba'
const descriptorRel = 'nodedc-source/services/node-intelligence/activation.json'
const gatewayRel = 'nodedc-source/server/routes/engineAgentGateway.js'
const files = [
  'nodedc-source/server/assets/engine-agent-npm/bin/nodedc-engine-codex-agent.mjs',
  'nodedc-source/server/assets/engine-agent-npm/package.json',
  'nodedc-source/server/assets/nodedc-engine-codex-agent-0.1.6.tgz',
  'nodedc-source/server/assets/provider-packages/v1/catalog.json',
  'nodedc-source/server/engineAgents/store.js',
  gatewayRel,
  descriptorRel,
]
const expectedSha256 = new Map([
  [files[0], 'c15c9da4f90f44a4e9e12f3683127e906d614fb98e562faa0c939505c973e074'],
  [files[1], '2ca8dcab0fa04bb1b21add1f75a9be61d5aa97753443ee1917302b4e0da5780a'],
  [files[2], 'd007a81cb4e4af569b3c54d3869b0f60b5597e3b531bff232145fa1851d8572a'],
  [files[3], '63e0741646197f0b1b3c64a4095e1bc8fb3a95ee6caf20b0293f89d869c9e620'],
  [files[4], '4cd4bdd5958cfafee184e98a04fe12aa0c1cbe884326beaec63c99f9fff61285'],
  [files[5], '5331f6dc8dc306f641370a2968eb025ee3e278e27ae9a217e4cfc2901fec369c'],
])

await assertFresh(target)
assertSha(await readFile(predecessorArtifact), predecessorArtifactSha256, 'predecessor MCP artifact')
const stage = await mkdtemp(join(tmpdir(), 'nodedc-engine-mcp-autonomy-provider-v5-'))
const payload = join(stage, 'payload')
try {
  await mkdir(payload, { recursive: true })
  for (const rel of files.slice(0, -1)) {
    const source = join(engineRoot, rel)
    const stat = await lstat(source)
    if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`source_boundary_invalid:${rel}`)
    assertSha(await readFile(source), expectedSha256.get(rel), rel)
    await mkdir(dirname(join(payload, rel)), { recursive: true })
    await cp(source, join(payload, rel), { force: false })
  }

  const descriptor = JSON.parse(extractMember(
    predecessorArtifact,
    `payload/${descriptorRel}`,
  ))
  if (
    descriptor?.action !== 'activate'
    || descriptor?.releaseId !== '2.33.2-974a9fb3492f'
    || descriptor?.source?.gatewaySha256 !== '96c726dab5cf1341f74e6e1095d518058ca320e0dd5738e25bdbe75db1f4fc15'
    || descriptor?.source?.upstreamProjectionSha256 !== '761a874b102a938bc6018159ddacdaac71ad6ae08e9f0f8d7f3b58a0165a5131'
  ) throw new Error('mcp_autonomy_predecessor_descriptor_mismatch')
  descriptor.source.gatewaySha256 = expectedSha256.get(gatewayRel)
  await mkdir(dirname(join(payload, descriptorRel)), { recursive: true })
  await writeFile(join(payload, descriptorRel), `${JSON.stringify(descriptor, null, 2)}\n`, 'utf8')

  await writeFile(join(stage, 'manifest.env'), `id=${id}\ncomponent=engine\ntype=app-overlay\n`, 'utf8')
  await writeFile(join(stage, 'files.txt'), `${files.join('\n')}\n`, 'utf8')
  await mkdir(artifactRoot, { recursive: true })
  run('python3', ['-c', canonicalTarScript(), target, stage])
  console.log(JSON.stringify({
    ok: true,
    id,
    artifact: target,
    artifactSha256: sha(await readFile(target)),
    services: ['nodedc-backend'],
    mcpVersion: '0.6.0',
    installerVersion: '0.1.6',
    authority: 'mcp-capability-intersect-user-objective',
    retryBoundary: 'three-identical-failures-without-new-evidence',
    providerPackages: ['gelios.provider.v4', 'gelios.provider.v5'],
    targetDataProduct: 'fleet.positions.current.v4',
    preserved: ['n8n', 'L1', 'node-intelligence image', 'databases', 'credential values'],
    files,
  }, null, 2))
} finally {
  await rm(stage, { recursive: true, force: true })
}

async function assertFresh(path) {
  try {
    await lstat(path)
  } catch (error) {
    if (error?.code === 'ENOENT') return
    throw error
  }
  throw new Error('artifact_already_exists')
}

function extractMember(archive, member) {
  const script = [
    'import pathlib,sys,tarfile',
    'p=pathlib.Path(sys.argv[1]); name=sys.argv[2]',
    "with tarfile.open(p,'r:gz') as t:",
    ' m=t.getmember(name)',
    " if not m.isfile(): raise SystemExit('member-not-file')",
    ' f=t.extractfile(m)',
    " if f is None: raise SystemExit('member-unreadable')",
    ' sys.stdout.buffer.write(f.read())',
  ].join('\n')
  return run('python3', ['-c', script, archive, member]).stdout
}

function canonicalTarScript() {
  return [
    'import gzip,io,pathlib,sys,tarfile',
    'root=pathlib.Path(sys.argv[2])',
    "with open(sys.argv[1],'xb') 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 assertSha(bytes, expected, label) {
  const actual = sha(bytes)
  if (!expected || actual !== expected) throw new Error(`${label.replaceAll(' ', '_')}_sha256_mismatch:${actual}`)
}

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

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