"""Decision context snapshot utility.

Provides the ``capture_context_snapshot`` function for capturing a
context snapshot at decision time. This utility is shared between
``StrategizeDecisionHook`` and the future ``ExecuteDecisionHook``.

Based on:
    - docs/specification.md §Strategize-Phase Recording Loop
    - docs/adr/ADR-033-decision-recording-protocol.md
    - Forgejo issue #8522
"""

from __future__ import annotations

import hashlib
import json
from typing import Any

from cleveragents.domain.models.core.decision import (
    ContextSnapshot,
    ResourceRef,
)


def capture_context_snapshot(
    context_data: dict[str, Any] | None = None,
    actor_state: dict[str, Any] | None = None,
    relevant_resources: list[str] | None = None,
) -> ContextSnapshot:
    """Capture a context snapshot at decision time.

    Automatically generates:

    - ``hot_context_hash``: SHA256 hash of the context data
    - ``hot_context_ref``: Abbreviated storage reference
    - ``relevant_resources``: List of resource references
    - ``actor_state_ref``: Reference to actor state checkpoint

    Args:
        context_data: Current context window contents (dict).
        actor_state: Actor's current state (dict).
        relevant_resources: List of resource IDs that influenced the decision.

    Returns:
        A :class:`~cleveragents.domain.models.core.decision.ContextSnapshot`
        with auto-captured fields.
    """
    # Generate hot context hash
    context_json = json.dumps(context_data or {}, sort_keys=True, default=str)
    hot_context_hash = f"sha256:{hashlib.sha256(context_json.encode()).hexdigest()}"

    # Generate actor state reference (placeholder for LangGraph checkpoint)
    actor_state_json = json.dumps(actor_state or {}, sort_keys=True, default=str)
    actor_state_ref = (
        f"checkpoint:{hashlib.sha256(actor_state_json.encode()).hexdigest()[:16]}"
    )

    # Convert resource IDs to ResourceRef objects
    resource_refs = [ResourceRef(resource_id=rid) for rid in (relevant_resources or [])]

    return ContextSnapshot(
        hot_context_hash=hot_context_hash,
        hot_context_ref=f"context:{hot_context_hash[7:23]}",  # Abbreviated ref
        relevant_resources=resource_refs,
        actor_state_ref=actor_state_ref,
    )
