#!/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 = '20260718-005', ...extra] = process.argv.slice(2)
if (extra.length || !/^\d{8}-[0-9]{3}$/.test(transitionId)) {
  throw new Error('usage: build-engine-mcp-ontology-sdk-artifact.mjs [YYYYMMDD-NNN]')
}

const id = `engine-mcp-control-plane-${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.5.tgz',
  'nodedc-source/server/assets/provider-packages/v1/catalog.json',
  'nodedc-source/server/dataProductPublishGrant/providerCatalog.js',
  'nodedc-source/server/engineAgents/store.js',
  gatewayRel,
  descriptorRel,
]
const expectedSha256 = new Map([
  [files[0], 'adff3e474c914680f7d36b204d1dc03e69dc8065fff1f80b6713526cfc970137'],
  [files[1], '0741647e4f7f58f69f3021d367484609a8e1eb7b8727d6ad9639bd9906b7f455'],
  [files[2], '72a1b2d41a12a298eaae63ba3334c7c66b6ca53de6a3f03a48607d4ff6da42fb'],
  [files[3], '4800e1a1c2af5e4893b1a403c04e91f55689383457caff833edc9e35e8e7e37a'],
  [files[4], 'd5511a8bd3b4238af88a89537661c9ca4c0126bca7b5ad225985e27ccdb2c64c'],
  [files[5], '4cd4bdd5958cfafee184e98a04fe12aa0c1cbe884326beaec63c99f9fff61285'],
  [files[6], '25fa013ddbfd7d0c7ece8c792daec5f345062757c85eb56cfbff45bf1e812152'],
])

await assertFresh(target)
assertSha(await readFile(predecessorArtifact), predecessorArtifactSha256, 'predecessor MCP artifact')
const stage = await mkdtemp(join(tmpdir(), 'nodedc-engine-mcp-ontology-sdk-'))
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_control_plane_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])
  const artifactSha256 = sha(await readFile(target))
  console.log(JSON.stringify({
    ok: true,
    id,
    artifact: target,
    artifactSha256,
    services: ['nodedc-backend'],
    predecessorGatewaySha256: '96c726dab5cf1341f74e6e1095d518058ca320e0dd5738e25bdbe75db1f4fc15',
    targetGatewaySha256: expectedSha256.get(gatewayRel),
    mcpVersion: '0.6.0',
    installerVersion: '0.1.5',
    ontologyMcp: 'separate-read-only-proxy',
    providerPackage: 'gelios.provider.v2',
    providerCredential: 'httpQueryAuth',
    preserved: ['n8n', 'L1', 'node-intelligence image', 'databases', 'provider 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],'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 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
}
