"""JSON output helpers for processed recordings."""

from __future__ import annotations

import json
import sys
from pathlib import Path
from typing import Any

from .document import normalize_path_string


def _sanitize_time_info(time_info: dict[str, Any] | None) -> dict[str, Any] | None:
    if time_info is None:
        return None
    return {key: value for key, value in time_info.items() if key != "active_intervals"}


def write_batch_json_output(
    output_path: Path,
    results: list[dict[str, Any]],
    combined_time_info: dict[str, Any] | None,
    all_verified: bool,
    batch_mode: bool = False,
    submitted_all_passed: bool | None = None,
    version: str | None = None,
) -> None:
    """Write processing results to a JSON file."""
    files_data: list[dict[str, Any]] = []
    all_editors: set[str] = set()

    for result in results:
        editors = list(result.get("editors", []))
        all_editors.update(editors)

        file_data = {
            "jsonl_file": normalize_path_string(str(result["jsonl_file"])),
            "document": result.get("target_document"),
            "verified": result.get("verified", False),
            "time_info": _sanitize_time_info(result.get("time_info")),
            "suspicious_events": result.get("suspicious_events", []),
            "template_diff": result.get("template_diff", ""),
            "reconstructed_code": result.get("reconstructed", ""),
        }
        if editors:
            file_data["editors"] = editors
        if result.get("warnings"):
            file_data["warnings"] = result["warnings"]
        if result.get("submitted_comparison") is not None:
            file_data["submitted_comparison"] = result["submitted_comparison"]

        files_data.append(file_data)

    payload: dict[str, Any] = {
        "version": version,
        "batch_mode": batch_mode,
        "total_files": len(results),
        "verified_count": sum(1 for result in results if result.get("verified")),
        "all_verified": all_verified,
        "files": files_data,
    }
    if combined_time_info is not None:
        payload["combined_time_info"] = _sanitize_time_info(combined_time_info)
    if all_editors:
        payload["editors"] = sorted(all_editors)
    if submitted_all_passed is not None:
        payload["submitted_all_passed"] = submitted_all_passed

    output_path.parent.mkdir(parents=True, exist_ok=True)
    output_path.write_text(json.dumps(payload, indent=2))

    if batch_mode:
        print(f"Batch results written to {output_path}", file=sys.stderr)
    else:
        print(f"Results written to {output_path}", file=sys.stderr)
