import fs from 'node:fs/promises'
import { buildHubLauncherAdminPlan } from './adapters/hub-launcher-admin.mjs'
import { validateCatalog } from './validate.mjs'

async function readInputJson() {
  const inputIndex = process.argv.indexOf('--input-json')
  if (inputIndex >= 0) {
    const inputPath = process.argv[inputIndex + 1]
    if (!inputPath) throw new Error('--input-json requires a path')
    return JSON.parse(await fs.readFile(inputPath, 'utf8'))
  }

  const inlineIndex = process.argv.indexOf('--input')
  if (inlineIndex >= 0) {
    return JSON.parse(process.argv[inlineIndex + 1] || '{}')
  }

  return null
}

function assertSmoke(condition, message) {
  if (!condition) throw new Error(message)
}

async function runSmoke() {
  const validation = await validateCatalog()
  assertSmoke(validation.ok, 'catalog must validate before adapter plan smoke')

  const cases = {
    blockUser: await buildHubLauncherAdminPlan({
      actionId: 'hub.user.block',
      assistantRole: 'admin',
      membershipRole: 'client_admin',
      actorUserId: 'user_root',
      targetUserId: 'user_pupa',
      confirmed: true,
      idempotencyKey: 'smoke:block:user_pupa',
    }),
    assistantRole: await buildHubLauncherAdminPlan({
      actionId: 'hub.assistant_access.change_role',
      assistantRole: 'admin',
      membershipRole: 'client_admin',
      actorUserId: 'user_root',
      targetUserId: 'user_pupa',
      membershipId: 'mem_client_public_pool_user_pupa',
      targetAssistantRole: 'blocked',
      confirmed: true,
      idempotencyKey: 'smoke:assistant-role:user_pupa',
    }),
    deleteUser: await buildHubLauncherAdminPlan({
      actionId: 'hub.user.delete',
      assistantRole: 'admin',
      membershipRole: 'client_admin',
      actorUserId: 'user_root',
      targetUserId: 'user_pupa',
      confirmed: true,
    }),
  }

  assertSmoke(cases.blockUser.ok, 'block user should produce a HUB adapter plan')
  assertSmoke(cases.blockUser.request.method === 'PATCH', 'block user should use PATCH')
  assertSmoke(cases.blockUser.request.body.globalStatus === 'blocked', 'block user should set globalStatus=blocked')
  assertSmoke(cases.assistantRole.ok, 'assistant role change should produce a HUB adapter plan')
  assertSmoke(cases.assistantRole.request.body.coreAssistantRole === 'blocked', 'assistant role should set coreAssistantRole=blocked')
  assertSmoke(!cases.deleteUser.ok, 'delete user must not produce an adapter plan')

  return { ok: true, validation: validation.counts, cases }
}

if (import.meta.url === `file://${process.argv[1]}`) {
  if (process.argv.includes('--smoke')) {
    console.log(JSON.stringify(await runSmoke(), null, 2))
  } else {
    const input = await readInputJson()
    if (!input) throw new Error('Use --smoke, --input <json>, or --input-json <path>')
    console.log(JSON.stringify(await buildHubLauncherAdminPlan(input), null, 2))
  }
}
