#!/usr/bin/env node
import { parseArgs } from 'node:util'
import { validate } from './validate.js'
import { execute } from './execute.js'
import { executeEnvelope, failExecute, printEnvelope } from '../../../lib/output.js'
import type { EntityAuditReport } from './types.js'

const COMMAND = 'smartstack-entity-audit'

async function main(): Promise<void> {
  const { values } = parseArgs({ options: { spec: { type: 'string' } }, strict: true })
  if (!values.spec) {
    printEnvelope(failExecute(COMMAND, ['--spec is required (JSON: { "projectPath": "...", "schemas": ["extensions"] })']))
    process.exit(1)
  }
  let raw: unknown
  try {
    raw = JSON.parse(values.spec)
  } catch {
    printEnvelope(failExecute(COMMAND, ['Invalid JSON in --spec']))
    process.exit(1)
  }
  const v = validate(raw)
  if (!v.valid || !v.spec) {
    printEnvelope(failExecute(COMMAND, v.errors))
    process.exit(1)
  }

  try {
    const { report, errors, warnings, nextSteps, reportPath } = await execute(v.spec)
    const ok = report.criticalCount === 0 && errors.length === 0
    printEnvelope(
      executeEnvelope<EntityAuditReport>(COMMAND, {
        success: ok,
        data: {
          criticalCount: report.criticalCount,
          reviewCount: report.reviewCount,
          exemptCount: report.exemptCount,
          okCount: report.okCount,
          reportPath,
        },
        report,
        errors,
        warnings,
        nextSteps,
      }),
    )
    process.exit(ok ? 0 : 1)
  } catch (e) {
    printEnvelope(failExecute(COMMAND, [(e as Error)?.message ?? String(e)]))
    process.exit(1)
  }
}

void main()
