#!/usr/bin/env node

const DEFAULT_URL = 'http://localhost:3001/api/v1/consistency';

const args = parseArgs(process.argv.slice(2));

if (args.help) {
  printHelp();
  process.exit(0);
}

const url = args.url || process.env.CONSISTENCY_URL || DEFAULT_URL;
const response = await fetch(url, {
  headers: {
    'x-ftb-user-id': process.env.CONSISTENCY_USER_ID || 'm-8',
    'x-ftb-user-role-id': process.env.CONSISTENCY_ROLE_ID || 'role-admin',
    'x-ftb-user-name': encodeURIComponent(process.env.CONSISTENCY_USER_NAME || '超级管理员'),
  },
});

if (!response.ok) {
  console.error(`V2.5 consistency check failed to call ${url}: HTTP ${response.status}`);
  console.error(await response.text().catch(() => ''));
  process.exit(1);
}

const result = await response.json();

if (args.json) {
  console.log(JSON.stringify(result, null, 2));
} else {
  printHuman(result);
}

process.exit(result.status === 'pass' ? 0 : 1);

function parseArgs(argv) {
  const parsed = { help: false, json: false, url: '' };
  for (let index = 0; index < argv.length; index += 1) {
    const arg = argv[index];
    if (arg === '--') continue;
    else if (arg === '--help' || arg === '-h') parsed.help = true;
    else if (arg === '--json') parsed.json = true;
    else if (arg === '--url') parsed.url = argv[++index];
    else if (arg.startsWith('--url=')) parsed.url = arg.slice('--url='.length);
    else throw new Error(`Unknown argument: ${arg}`);
  }
  return parsed;
}

function printHuman(result) {
  console.log(result.summary?.human ?? `V2.5 consistency ${result.status}`);
  console.log(`Generated at: ${result.generatedAt}`);
  console.log(`Counts: ${Object.entries(result.counts ?? {}).map(([key, value]) => `${key}=${value}`).join(', ')}`);

  for (const [group, checks] of Object.entries(result.checks ?? {})) {
    const failed = checks.filter((item) => item.severity !== 'ok');
    if (failed.length === 0) {
      console.log(`${group}: ok`);
      continue;
    }
    console.log(`${group}:`);
    for (const item of failed) {
      console.log(`- [${item.severity}] ${item.id}: ${item.message}`);
    }
  }
}

function printHelp() {
  console.log(`Usage: pnpm consistency:v25 -- --url http://localhost:3001/api/v1/consistency

Calls the V2.5 consistency endpoint and prints both human-readable and JSON-ready
results for counts, partition keys, orphan references, and audit coverage.

Options:
  --url <url>   Consistency endpoint URL. Defaults to ${DEFAULT_URL}.
  --json        Print raw JSON response.
  -h, --help    Show this help.
`);
}
