#!/usr/bin/env ts-node
// flutter-analyze.ts — Pre-commit hook: runs dart analyze and dart format check
import { execSync } from 'child_process';

const RED   = '\x1b[31m';
const GREEN = '\x1b[32m';
const RESET = '\x1b[0m';

function run(cmd: string): { stdout: string; code: number } {
  try {
    const stdout = execSync(cmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'] });
    return { stdout, code: 0 };
  } catch (e: any) {
    return { stdout: e.stdout ?? e.message, code: e.status ?? 1 };
  }
}

console.log('🔍 Running flutter analyze...');
const analyze = run('flutter analyze --no-congratulate');
if (analyze.code !== 0) {
  console.error(`${RED}✘ flutter analyze failed:\n${analyze.stdout}${RESET}`);
  process.exit(1);
}

console.log('🎨 Checking dart format...');
const format = run('dart format --output=none --set-exit-if-changed lib/ test/');
if (format.code !== 0) {
  console.error(`${RED}✘ Unformatted files detected. Run: dart format lib/ test/${RESET}`);
  process.exit(1);
}

console.log(`${GREEN}✔ flutter analyze + dart format passed${RESET}`);
