#!/usr/bin/env node
/**
 * repo-stats CLI
 *
 * Usage:
 *   repo-stats owner/repo [--json] [--md] [--open-only] [--no-color]
 */

import { Command } from 'commander';
import { parseRepoUrl } from './parse.js';
import { fetchRepoStats } from './github.js';
import { buildSummary } from './summary.js';
import { renderTable, renderJson, renderMarkdown, type RenderFormat } from './render.js';

const program = new Command();

program
  .name('repo-stats')
  .description('A maintainer dashboard for any public GitHub repository.')
  .version('0.1.0')
  .argument('<repo>', 'Repository in the form owner/name (or full GitHub URL).')
  .option('--json', 'Emit a JSON blob instead of a table.')
  .option('--md', 'Emit a Markdown summary instead of a table.')
  .option('--open-only', 'Only count open issues and PRs.')
  .option('--no-color', 'Disable ANSI color output (table mode only).')
  .option('--limit-issues <n>', 'Maximum issues to fetch (default 30).', (v: string) => Number(v))
  .option('--limit-pulls <n>', 'Maximum PRs to fetch (default 20).', (v: string) => Number(v))
  .option('--limit-releases <n>', 'Maximum releases to fetch (default 10).', (v: string) => Number(v))
  .option('--limit-contributors <n>', 'Maximum contributors to fetch (default 20).', (v: string) => Number(v))
  .action(async (repoArg: string, opts: {
    json?: boolean;
    md?: boolean;
    openOnly?: boolean;
    color?: boolean;
    limitIssues?: number;
    limitPulls?: number;
    limitReleases?: number;
    limitContributors?: number;
  }) => {
    try {
      let format: RenderFormat = 'table';
      if (opts.json) format = 'json';
      else if (opts.md) format = 'markdown';

      const repo = parseRepoUrl(repoArg);
      const fetched = await fetchRepoStats(repo, {
        openIssuesOnly: Boolean(opts.openOnly),
        openPullsOnly: Boolean(opts.openOnly),
        issueLimit: opts.limitIssues,
        pullLimit: opts.limitPulls,
        releaseLimit: opts.limitReleases,
        contributorLimit: opts.limitContributors,
      });
      const summary = buildSummary(fetched);

      if (format === 'json') {
        process.stdout.write(renderJson(fetched));
      } else if (format === 'markdown') {
        process.stdout.write(renderMarkdown(summary));
      } else {
        process.stdout.write(renderTable(summary));
      }
    } catch (err) {
      const e = err as Error;
      console.error(`repo-stats: ${e.message}`);
      process.exitCode = 1;
    }
  });

program.parseAsync(process.argv).catch((err: unknown) => {
  const e = err as Error;
  console.error(e);
  process.exit(1);
});
