import fs from 'node:fs'
import path from 'node:path'

const root = process.cwd()
const required = [
  'packages/kbx-contracts/src/runtime.ts',
  'packages/kbx-contracts/src/performance.ts',
  'packages/kbx-ui/src/components/KbxRuntimeBanner.vue',
  'packages/kbx-ui/src/components/KbxFreshnessIndicator.vue',
  'packages/kbx-ui/src/components/KbxConflictResolver.vue',
  'packages/kbx-ui/src/components/KbxOperationCenter.vue',
  'packages/kbx-ui/src/components/KbxNotificationCenter.vue',
  'apps/web/src/runtime/KbxRuntimeShell.vue',
  'apps/web/src/http/kbxHttpClient.ts',
  'backend/Database/Migrations/20260808_008_kbx_runtime_operations.sql',
  'backend/Shared/Runtime/KbxOperationPolicy.cs',
  'backend/Shared/Runtime/KbxTelemetry.cs',
  'backend/Shared/Runtime/KbxCorrelationMiddleware.cs',
  'docs/production-readiness-v9.md',
  'docs/failure-recovery-matrix-v9.md',
  'docs/performance-budget-v9.md',
  'docs/observability-runtime-v9.md',
]

const missing = required.filter(file => !fs.existsSync(path.join(root, file)))
if (missing.length) {
  console.error('KBX v9 production readiness files missing:\n' + missing.join('\n'))
  process.exit(1)
}

const migration = fs.readFileSync(path.join(root, 'backend/Database/Migrations/20260808_008_kbx_runtime_operations.sql'), 'utf8')
for (const token of ['kbx.operation_runs', 'kbx.user_notifications', 'kbx.runtime_incidents', 'idempotency_key', 'correlation_id']) {
  if (!migration.includes(token)) throw new Error(`runtime migration missing ${token}`)
}

const http = fs.readFileSync(path.join(root, 'apps/web/src/http/kbxHttpClient.ts'), 'utf8')
if (/interceptors\.response[\s\S]*axios\([^)]*\)/.test(http)) {
  throw new Error('response interceptor must not implement hidden mutation retries')
}
if (!http.includes('Idempotency-Key')) throw new Error('idempotency helper missing')
if (!http.includes('X-Correlation-Id')) throw new Error('correlation id propagation missing')

const policy = fs.readFileSync(path.join(root, 'backend/Shared/Runtime/KbxOperationPolicy.cs'), 'utf8')
if (!policy.includes('hasIdempotencyKey')) throw new Error('server retry policy must require idempotency for mutation')

console.log('production readiness guard PASS')
