#!/usr/bin/env node
/**
 * cli:cross-validate-stack
 * Validation cross-stack backend .NET / frontend React — 5 checks de coherence.
 *
 * Usage :
 *   npx tsx skills/validation/cross-validate/cli/index.ts --specs <directory> --src <directory>
 *
 * Exit codes :
 *   0  Succes (0 erreurs)
 *   1  Erreurs detectees
 *   2  Erreur interne CLI / validation input
 */
import { parseArgs } from 'node:util'
import { resolve } from 'node:path'
import { validate } from './validate'
import { execute } from './execute'
import { executeEnvelope, failExecute, printEnvelope } from '../../../lib/output.js'

const COMMAND = 'cross-validate-stack'

const { values } = parseArgs({
  options: {
    specs: { type: 'string' },
    src: { type: 'string' },
    help: { type: 'boolean', short: 'h' },
  },
  strict: true,
})

if (values.help) {
  const paren = String.fromCharCode(41)
  console.log(`cli:cross-validate-stack — SmartStack Studio

Validation cross-stack backend .NET / frontend React (5 checks${paren}.

Usage:
  npx tsx index.ts --specs <directory> --src <directory>

Options:
  --specs    Repertoire contenant les specs JSON (meta.json, endpoints.json, permissions.json${paren} (requis${paren}
  --src      Repertoire contenant le code source .cs et .ts/.tsx (requis${paren}
  -h, --help Affiche cette aide

Checks:
  1. routes-have-endpoints     Chaque endpoint spec a un controller .NET
  2. endpoints-are-consumed    Chaque endpoint .NET est appele par un service React
  3. permissions-aligned       [RequirePermission] .NET = PermissionGuard/usePermission React
  4. resources-have-screens    Chaque ressource a controller + page React
  5. rbac-consistent           Permissions declarees = permissions utilisees dans le code

Exit codes:
  0  Succes (0 erreurs${paren}
  1  Erreurs detectees
  2  Erreur interne CLI`)
  process.exit(0)
}

if (!values.specs) {
  printEnvelope(failExecute(COMMAND, ['--specs is required']))
  process.exit(2)
}

if (!values.src) {
  printEnvelope(failExecute(COMMAND, ['--src is required']))
  process.exit(2)
}

const specsPath = resolve(values.specs)
const srcPath = resolve(values.src)

const validation = validate({ specs: specsPath, src: srcPath })

if (!validation.valid) {
  printEnvelope(failExecute(COMMAND, validation.blockers))
  process.exit(2)
}

const report = execute(validation.data!)

if (report.errors === 0) {
  printEnvelope(executeEnvelope(COMMAND, { report, warnings: report.warnings > 0 ? [`${report.warnings} warning(s)`] : [] }))
} else {
  printEnvelope({ ...failExecute(COMMAND, [`${report.errors} error(s) detected`]), report })
}

process.exit(report.errors > 0 ? 1 : 0)
