"""Pure helpers for workflow structure hashing."""

from __future__ import annotations

import hashlib
import json
from typing import Any

from agentbyte.workflow.core.models import (
    WorkflowCompletionMode,
    WorkflowStateConflictPolicy,
    WorkflowStateMode,
)


def build_workflow_structure_hash(
    *,
    steps: dict[str, Any],
    edges: list[Any],
    start_step_id: str | None,
    end_step_ids: list[str],
    completion_mode: WorkflowCompletionMode,
    state_mode: WorkflowStateMode,
    state_conflict_policy: WorkflowStateConflictPolicy,
) -> str:
    """Compute a stable topology hash without constructing a Workflow object."""
    data = {
        "steps": [
            {
                "id": sid,
                "input_type": step.input_type.__name__,
                "output_type": step.output_type.__name__,
                "join_failure_mode": step.metadata.join_failure_mode.value,
            }
            for sid, step in sorted(steps.items())
        ],
        "edges": [
            {
                "from": edge.from_step,
                "to": edge.to_step,
                "condition_type": edge.condition.type,
            }
            for edge in sorted(edges, key=lambda e: (e.from_step, e.to_step))
        ],
        "start": start_step_id,
        "end": sorted(end_step_ids),
        "completion_mode": completion_mode.value,
        "state_mode": state_mode.value,
        "state_conflict_policy": state_conflict_policy.value,
    }
    digest = hashlib.sha256(json.dumps(data, sort_keys=True).encode("utf-8")).hexdigest()
    return digest[:16]


__all__ = ["build_workflow_structure_hash"]
