import fs from 'node:fs';
import { normalizeTasks } from './normalize.mjs';
import { summarize } from './summary.mjs';
import { renderText } from './render.mjs';

try {
  const args = process.argv.slice(2);
  if (args.length < 1 || args.length > 2 || !args[0] || args[0].startsWith('-') ||
      (args.length === 2 && args[1] !== '--json')) {
    throw new TypeError('用法：node src/cli.mjs <JSON文件> [--json]');
  }

  const source = fs.readFileSync(args[0], 'utf8');
  const tasks = normalizeTasks(JSON.parse(source));
  const summary = summarize(tasks);
  const output = args[1] === '--json' ? JSON.stringify(summary) : renderText(summary);
  process.stdout.write(output + '\n');
  process.exitCode = 0;
} catch (error) {
  process.stderr.write(`输入错误：${error.message}\n`);
  process.exitCode = 2;
}
