from __future__ import annotations

from datetime import datetime, timezone
from typing import Any, Mapping

from .contracts import RunManifest, stable_json_fingerprint



def compute_operator_chain_fingerprint(operator_chain: Any) -> str:
    """Compute a deterministic fingerprint for an operator chain spec."""
    if isinstance(operator_chain, Mapping):
        normalized: Any = dict(operator_chain)
    elif isinstance(operator_chain, (list, tuple)):
        normalized = list(operator_chain)
    else:
        normalized = {"value": operator_chain}
    return stable_json_fingerprint(normalized)



def _utc_now_rfc3339() -> str:
    return datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")



def build_run_manifest(
    *,
    run_id: str,
    dataset_ref: str,
    snapshot_hash: str,
    operator_chain: Any,
    usage: str | None = None,
    profile: str | None = None,
    source_version: str | None = None,
    connector_policy: Mapping[str, Any] | None = None,
    created_at: str | None = None,
) -> RunManifest:
    """Build a validated run manifest with deterministic operator chain fingerprint."""
    return RunManifest(
        run_id=run_id,
        dataset_ref=dataset_ref,
        usage=usage,
        profile=profile,
        source_version=source_version,
        snapshot_hash=snapshot_hash,
        connector_policy=dict(connector_policy or {}),
        operator_chain_fingerprint=compute_operator_chain_fingerprint(operator_chain),
        created_at=created_at or _utc_now_rfc3339(),
    )


__all__ = [
    "compute_operator_chain_fingerprint",
    "build_run_manifest",
]
