"""JSON report formatter per §A.1.6 envelope spec."""

from __future__ import annotations

from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any

from pydantic import BaseModel, ConfigDict

from complyform import __version__

if TYPE_CHECKING:
    from complyform.core.assessor.control_matcher import Finding


class AssessmentSummary(BaseModel):
    """Summary section of the assessment JSON envelope."""

    model_config = ConfigDict(strict=True)

    total_controls: int
    passed: int
    failed: int
    manual_review: int
    not_assessed: int
    score: float
    severity_counts: dict[str, int]


class AssessmentMetadata(BaseModel):
    """Metadata section of the assessment JSON envelope."""

    model_config = ConfigDict(strict=True)

    resource_count: int
    assessment_duration_ms: int
    tier: str
    cache_hit: bool
    provider_versions: dict[str, str]


def format_json_envelope(
    findings: list[Finding],
    summary: AssessmentSummary,
    metadata: AssessmentMetadata,
    *,
    cloud: str,
    state_hash: str,
    frameworks: list[str],
    upgrade_hints: list[dict[str, object]] | None = None,
    cloud_intelligence: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """Build §A.1.6 JSON envelope."""
    return {
        "schema_version": 1,
        "tool": "complyform",
        "tool_version": __version__,
        "command": "assess",
        "timestamp": datetime.now(UTC).isoformat(),
        "cloud": cloud,
        "scan_source": "state",
        "state_hash": state_hash,
        "frameworks": frameworks,
        "summary": summary.model_dump(mode="json"),
        "findings": [f.model_dump(mode="json") for f in findings],
        "metadata": metadata.model_dump(mode="json"),
        "cloud_intelligence": cloud_intelligence,
        "upgrade_hints": upgrade_hints,
    }
