"""JSON exporter for audit history."""

import json
from datetime import datetime
from pathlib import Path
from typing import Any

from tools.view_history.utils import normalize_affected_files


class JsonExporter:
    """Exports audits to JSON format."""

    def __init__(self, project_name: str, audits: list[dict[str, Any]]) -> None:
        self.project_name = project_name
        self.audits = audits

    def export(self, output_path: Path) -> None:
        """Export audits to a JSON file."""
        data = self.to_dict()
        output_path.write_text(json.dumps(data, indent=2, ensure_ascii=False))

    def to_dict(self) -> dict[str, Any]:
        """Convert audits to JSON-serializable dict."""
        return {
            "exported_at": datetime.now().isoformat(),
            "project": self.project_name,
            "total_audits": len(self.audits),
            "audits": [self._export_single(audit) for audit in self.audits],
        }

    def to_json(self, indent: int = 2) -> str:
        """Convert audits to JSON string."""
        return json.dumps(self.to_dict(), indent=indent, ensure_ascii=False)

    def _export_single(self, audit: dict[str, Any]) -> dict[str, Any]:
        """Export a single audit to JSON-serializable dict."""
        summary = audit.get("summary", {})
        return {
            "id": audit.get("dir_name", ""),
            "lens": audit.get("lens", "unknown"),
            "timestamp": audit.get("timestamp", ""),
            "confidence": audit.get("confidence", "exploring"),
            "findings_count": summary.get("total_findings", 0)
            or audit.get("total_findings", 0),
            "files_examined": summary.get("files_examined", 0)
            or audit.get("files_examined", 0),
            "steps_completed": summary.get("steps_completed", 0),
            "duration_seconds": summary.get("duration_seconds"),
            "by_severity": summary.get("by_severity", {})
            or audit.get("by_severity", {}),
            "findings": self._normalize_findings(audit.get("findings", [])),
        }

    def _normalize_findings(self, findings: list[dict]) -> list[dict]:
        """Normalize findings for export."""
        return [
            {
                "severity": f.get("severity", "info"),
                "category": f.get("category", ""),
                "description": f.get("description", ""),
                "remediation": f.get("remediation", ""),
                "affected_files": normalize_affected_files(
                    f.get("affected_files", [])
                ),
                "cwe_id": f.get("cwe_id", ""),
            }
            for f in findings
        ]

