"""JSON report generator."""

from __future__ import annotations

from datetime import datetime, timezone

from sanicode.report.persist import ScanResult

_SEVERITY_ORDER = {"critical": 0, "high": 1, "medium": 2, "low": 3, "info": 4}


def generate_json(result: ScanResult) -> dict:
    """Generate a JSON-serializable report dict, sorted for presentation.

    Findings are sorted by severity (critical first), then by file path,
    then by line number. Uses ``derived_severity`` when present, falling
    back to ``severity``.

    Args:
        result: Completed ScanResult produced by the scanner.

    Returns:
        A dict suitable for ``json.dumps()``. Distinct from the raw
        scan-result.json in that findings are presentation-sorted.
    """
    sorted_findings = sorted(
        result.findings,
        key=lambda f: (
            _SEVERITY_ORDER.get(f.get("derived_severity") or f.get("severity", "info"), 4),
            f.get("file", ""),
            f.get("line", 0),
        ),
    )

    return {
        "sanicode_version": result.sanicode_version,
        "scan_id": result.scan_id,
        "scanned_path": result.scanned_path,
        "scan_timestamp": result.scan_timestamp,
        "report_generated_at": datetime.now(timezone.utc).isoformat(),
        "summary": result.summary,
        "findings": sorted_findings,
    }
