#!/usr/bin/env node
/**
 * cli:eslint-validator
 * Responsabilite : orchestrer validation + execution des 5 regles ESLint SmartStack
 * Appele par Claude Code via skill:eslint-validator
 *
 * Usage :
 *   npx tsx skills/validation/eslint/cli/index.ts --src <directory>
 */
import { parseArgs } from 'node:util'
import { resolve } from 'node:path'
import { validate } from './validate'
import { execute } from './execute'
import type { ESLintReport } from './types'

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

if (values.help) {
  console.log(`cli:eslint-validator — SmartStack Studio

Analyse statique des fichiers React/TypeScript (5 regles SmartStack).

Regles:
  ss/no-direct-fetch       — Pas de fetch/axios dans components/ et pages/
  ss/permission-guard      — Actions sensibles wrappees dans PermissionGuard
  ss/dto-naming            — Interfaces alignees avec les conventions DTO
  ss/service-hook-structure — Hooks standard useQuery/useMutation
  ss/feature-folder        — Structure features/{module}/{resource}/{layer}/

Usage:
  npx tsx skills/validation/eslint/cli/index.ts --src <directory>

Options:
  --src       Repertoire contenant les fichiers .tsx/.ts (requis)
  -h, --help  Affiche cette aide

Exit codes:
  0  Succes (aucune erreur)
  1  Erreur de validation (input invalide)
  2  Erreur interne CLI
  3  Violations detectees`)
  process.exit(0)
}

if (!values.src) {
  console.error(JSON.stringify({
    timestamp: new Date().toISOString(),
    checks: [],
    errors: 1,
    warnings: 0,
    message: '--src is required',
  }))
  process.exit(1)
}

// ─── Resolve path ───
const srcPath = resolve(values.src)

// ─── Validate ───
const validation = validate({ src: srcPath })
if (!validation.valid) {
  const report: ESLintReport = {
    timestamp: new Date().toISOString(),
    checks: validation.blockers.map((b) => ({
      code: 'cli/validation',
      status: 'error' as const,
      message: b,
    })),
    errors: validation.blockers.length,
    warnings: 0,
  }
  console.log(JSON.stringify(report, null, 2))
  process.exit(1)
}

// ─── Execute ───
try {
  const report = execute(validation.data!)
  console.log(JSON.stringify(report, null, 2))

  // Exit code based on results
  if (report.errors > 0) {
    process.exit(3)
  }
  process.exit(0)
} catch (err) {
  const message = err instanceof Error ? err.message : String(err)
  console.error(JSON.stringify({
    timestamp: new Date().toISOString(),
    checks: [{ code: 'cli/internal', status: 'error', message }],
    errors: 1,
    warnings: 0,
  }))
  process.exit(2)
}
