"""Build in-toto Statement v1 from assessment result."""

from __future__ import annotations

import hashlib
from datetime import UTC, datetime
from typing import Any

from complyform import __version__
from complyform.core.attestation.canonical import canonical_json
from complyform.core.attestation.signer import build_dsse_envelope


def build_attestation(
    assessment_json: dict[str, Any],
    assessment_path: str,
    signing_key_pem: bytes | None = None,
) -> dict[str, Any]:
    """Build in-toto Statement v1 wrapped in DSSE envelope.

    When signing_key_pem is provided, the envelope is signed with Ed25519.
    Otherwise, an unsigned envelope with empty signatures is returned.
    """
    assessment_bytes = canonical_json(assessment_json)
    digest = hashlib.sha256(assessment_bytes).hexdigest()

    summary = assessment_json.get("summary", {})
    statement: dict[str, Any] = {
        "_type": "https://in-toto.io/Statement/v1",
        "subject": [
            {
                "name": assessment_path,
                "digest": {"sha256": digest},
            }
        ],
        "predicateType": "https://complyform.dev/attestation/assessment/v1",
        "predicate": {
            "tool": "complyform",
            "tool_version": __version__,
            "timestamp": datetime.now(UTC).isoformat(),
            "cloud": assessment_json.get("cloud", ""),
            "frameworks": assessment_json.get("frameworks", []),
            "score": summary.get("score", 0.0),
            "summary": {
                "total_controls": summary.get("total_controls", 0),
                "passed": summary.get("passed", 0),
                "failed": summary.get("failed", 0),
                "manual_review": summary.get("manual_review", 0),
            },
            "state_hash": assessment_json.get("state_hash", ""),
            "profile_bundle_version": None,
            "signing_key_id": None,
        },
    }

    statement_json = canonical_json(statement).decode("utf-8")
    return build_dsse_envelope(statement_json, signing_key_pem)
