/**
 * Imperatriz Bot — Validador de Fluxo (CLI)
 *
 * Uso:
 *   npx tsx validators/flow-validator.ts <caminho-pro-flow.json>
 *
 * Saida: exit 0 se valido; exit 1 com lista de issues caso invalido.
 *
 * Re-exporta a logica de schema-blocks.ts pra ser usada como CLI standalone
 * E pra ser importada pela skill no momento de geracao.
 */

import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { parseAndValidate, type ValidationIssue } from "../templates/schema-blocks";

function printIssues(issues: ValidationIssue[]): void {
  const errors = issues.filter((i) => i.level === "error");
  const warnings = issues.filter((i) => i.level === "warning");

  if (errors.length > 0) {
    console.error(`\n❌ ${errors.length} erro(s):`);
    errors.forEach((i) =>
      console.error(`  [${i.block_id ?? "global"}] ${i.message}`),
    );
  }

  if (warnings.length > 0) {
    console.warn(`\n⚠️  ${warnings.length} aviso(s):`);
    warnings.forEach((i) =>
      console.warn(`  [${i.block_id ?? "global"}] ${i.message}`),
    );
  }

  if (errors.length === 0 && warnings.length === 0) {
    console.log("✅ Fluxo valido — sem erros ou avisos.");
  }
}

export function validateFile(path: string): {
  ok: boolean;
  issues: ValidationIssue[];
} {
  const absPath = resolve(path);
  const raw = readFileSync(absPath, "utf-8");
  let json: unknown;
  try {
    json = JSON.parse(raw);
  } catch (err) {
    return {
      ok: false,
      issues: [
        {
          level: "error",
          message: `JSON invalido em ${absPath}: ${(err as Error).message}`,
        },
      ],
    };
  }

  const result = parseAndValidate(json);
  return { ok: result.ok, issues: result.issues };
}

// CLI entrypoint
if (process.argv[1]?.endsWith("flow-validator.ts")) {
  const path = process.argv[2];
  if (!path) {
    console.error("Uso: npx tsx validators/flow-validator.ts <flow.json>");
    process.exit(2);
  }

  const { ok, issues } = validateFile(path);
  printIssues(issues);
  process.exit(ok ? 0 : 1);
}
