#!/usr/bin/env node
/**
 * audit-dev-tests — index.ts
 *
 * Runs DEV-TEST-001..003 against a project + its BA module, returns a JSON
 * AuditReport on stdout. Exit code 1 on any `err` finding (BLOCKING gate).
 */

import { parseArgs } from 'node:util'
import { audit } from './audit.js'
import type { AuditReport } from './types.js'
import { validate } from './validate.js'

async function main(): Promise<void> {
  const args = parseArgs({
    options: {
      spec: { type: 'string' },
      json: { type: 'boolean', default: false },
    },
    allowPositionals: false,
  })

  if (!args.values.spec) {
    console.error('Error: --spec is required')
    process.exit(2)
  }

  let raw: unknown
  try {
    raw = JSON.parse(args.values.spec)
  } catch {
    console.error('Error: --spec must be valid JSON')
    process.exit(2)
  }

  const v = validate(raw)
  if (!v.valid) {
    emit(args.values.json, {
      success: false,
      error: v.errors.join('; '),
      baAcCount: 0,
      testTraitCount: 0,
      todoMarkerCount: 0,
      findings: [],
    })
    process.exit(2)
  }

  const report = await audit(v.data!)
  emit(args.values.json, report)
  process.exit(report.success ? 0 : 1)
}

function emit(json: boolean | undefined, payload: AuditReport): void {
  if (json) {
    console.log(JSON.stringify(payload, null, 2))
    return
  }
  if (!payload.success && payload.error) {
    console.error(`✗ ${payload.error}`)
    return
  }
  console.log(payload.success ? '✓ audit-dev-tests:' : '✗ audit-dev-tests:')
  console.log(`  BA ACs scanned       : ${payload.baAcCount}`)
  console.log(`  Test traits scanned  : ${payload.testTraitCount}`)
  console.log(`  TODO[AC- markers     : ${payload.todoMarkerCount}`)
  console.log('')
  for (const f of payload.findings) {
    const tag = f.severity === 'err' ? '❌' : f.severity === 'warn' ? '⚠️ ' : '✅'
    console.log(`  ${tag} ${f.rule} (${f.severity}): ${f.message}`)
    if (f.refs.length > 0 && f.refs.length <= 10) {
      for (const r of f.refs) console.log(`       - ${r}`)
    } else if (f.refs.length > 10) {
      for (const r of f.refs.slice(0, 10)) console.log(`       - ${r}`)
      console.log(`       … and ${f.refs.length - 10} more`)
    }
    if (f.fix && f.severity !== 'ok') console.log(`       → ${f.fix}`)
  }
}

main().catch(err => {
  console.error('Fatal:', (err as Error).message)
  process.exit(2)
})
