from __future__ import annotations

import hashlib
import json
from typing import Any


def _normalize_key(key: Any) -> str:
    return str(key or "").strip()


def _normalize_value(value: Any) -> str:
    if value is None:
        return ""
    return str(value).strip()


def compute_row_hash(row: dict[str, Any]) -> str:
    """Return a stable deterministic hash for a logical CSV row.

    Whitespace, key order, and None-vs-empty differences are normalized so the
    same logical source row cannot be imported twice merely because formatting
    changed. Values remain case-sensitive; ticker/ISIN canonicalization belongs
    in import-specific validation, not in the generic hash.
    """
    normalized = {_normalize_key(k): _normalize_value(v) for k, v in row.items()}
    payload = json.dumps(normalized, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(payload.encode("utf-8")).hexdigest()
