import { writeFileSync } from 'fs';
import { join } from 'path';
import type { CoverageReport } from '../types';

export class JsonReporter {
  report(coverage: CoverageReport, outputDir: string): void {
    const outputPath = join(outputDir, 'coverage.json');
    
    // Create a clean report without circular references
    const cleanReport = {
      timestamp: coverage.timestamp,
      summary: {
        lines: {
          total: coverage.overall.lines.total,
          covered: coverage.overall.lines.covered,
          percentage: coverage.overall.lines.percentage,
        },
        functions: {
          total: coverage.overall.functions.total,
          covered: coverage.overall.functions.covered,
          percentage: coverage.overall.functions.percentage,
        },
        branches: {
          total: coverage.overall.branches.total,
          covered: coverage.overall.branches.covered,
          percentage: coverage.overall.branches.percentage,
        },
        statements: {
          total: coverage.overall.statements.total,
          covered: coverage.overall.statements.covered,
          percentage: coverage.overall.statements.percentage,
        },
      },
      packages: coverage.packages.map(pkg => ({
        name: pkg.name,
        path: pkg.path,
        lines: {
          total: pkg.lines.total,
          covered: pkg.lines.covered,
          percentage: pkg.lines.percentage,
        },
        functions: {
          total: pkg.functions.total,
          covered: pkg.functions.covered,
          percentage: pkg.functions.percentage,
        },
        branches: {
          total: pkg.branches.total,
          covered: pkg.branches.covered,
          percentage: pkg.branches.percentage,
        },
        statements: {
          total: pkg.statements.total,
          covered: pkg.statements.covered,
          percentage: pkg.statements.percentage,
        },
        files: pkg.files.map(file => ({
          path: file.path,
          lines: {
            total: file.lines.total,
            covered: file.lines.covered,
            percentage: file.lines.percentage,
          },
          functions: {
            total: file.functions.total,
            covered: file.functions.covered,
            percentage: file.functions.percentage,
          },
          branches: {
            total: file.branches.total,
            covered: file.branches.covered,
            percentage: file.branches.percentage,
          },
          statements: {
            total: file.statements.total,
            covered: file.statements.covered,
            percentage: file.statements.percentage,
          },
        })),
      })),
      config: {
        thresholds: coverage.config.thresholds,
        exclude: coverage.config.exclude,
        reporters: coverage.config.reporters,
      },
    };

    writeFileSync(outputPath, JSON.stringify(cleanReport, null, 2));
    console.log(`JSON coverage report written to: ${outputPath}`);
  }
}