"""JSON formatter for machine-readable output."""

from __future__ import annotations

import json
from typing import List, TextIO
import sys

from stablestack.models import Finding


class JSONFormatter:
    """Formats findings as JSON for CI/CD integration."""

    def __init__(self, pretty: bool = False):
        """
        Initialize the formatter.

        Args:
            pretty: Whether to pretty-print the JSON output
        """
        self.pretty = pretty

    def format(self, findings: List[Finding], output: TextIO = sys.stdout) -> None:
        """
        Format and write findings as JSON to output.

        Args:
            findings: List of findings to format
            output: Output stream (default: stdout)
        """
        result = {
            "version": "1.0",
            "findings": [f.to_dict() for f in findings],
            "summary": self._get_summary(findings),
        }

        if self.pretty:
            json.dump(result, output, indent=2)
        else:
            json.dump(result, output)

        output.write("\n")

    def _get_summary(self, findings: List[Finding]) -> dict:
        """Generate summary statistics."""
        by_severity = {"error": 0, "warning": 0, "info": 0}
        by_rule: dict[str, int] = {}
        files: set[str] = set()

        for finding in findings:
            by_severity[str(finding.severity)] += 1
            by_rule[finding.rule_id] = by_rule.get(finding.rule_id, 0) + 1
            files.add(finding.file)

        return {
            "total": len(findings),
            "by_severity": by_severity,
            "by_rule": by_rule,
            "files_with_issues": len(files),
        }
