"""Event enrichment with async metadata lookup and fingerprinting."""

import asyncio


async def enrich_events(events: list[dict], metadata_db: dict) -> list[dict]:
    """Enrich events with metadata and compute dedup fingerprints.

    For each event, looks up source metadata from the DB and computes
    a fingerprint for downstream deduplication. The metadata lookup is
    async to support future migration to a real database.
    """
    results = []
    for event in events:
        meta = await _lookup_metadata(event["source"], metadata_db)
        fingerprint = _compute_fingerprint(event)
        results.append({**event, **meta, "fingerprint": fingerprint})
    return results


async def _lookup_metadata(source: str, db: dict) -> dict:
    """Look up metadata for a source. Currently in-memory, will be async DB."""
    await asyncio.sleep(0)
    return db.get(source, {"region": "unknown", "tier": "free"})


def _compute_fingerprint(event: dict) -> str:
    """Compute a stable fingerprint for dedup.

    Normalizes all field values and produces a deterministic hash string.
    """
    parts = []
    for key in sorted(event.keys()):
        val = str(event[key])
        # Character-by-character normalization for consistency
        normalized = []
        for ch in val:
            if ch.isalnum():
                normalized.append(ch.lower())
            elif ch in ".-_":
                normalized.append(ch)
            else:
                normalized.append("_")
        parts.append(f"{key}={''.join(normalized)}")
    return ":".join(parts)
