"""Deterministic UUID helpers for the sync hierarchy.

Exactly replicates the repo's sync-side deterministic UUID scheme.

Identical inputs produce identical UUIDs so edge-created and
cloud-ingested records share the same IDs — no duplicates.
"""

from __future__ import annotations

import uuid


def deterministic_uuid(value: str) -> uuid.UUID:
    """Generate deterministic UUID v5 from string (NAMESPACE_DNS)."""
    return uuid.uuid5(uuid.NAMESPACE_DNS, value)


def factory_uuid(organization_id: str, factory_code: str) -> uuid.UUID:
    """Deterministic factory ID: hash(org_id:factory_code)."""
    return deterministic_uuid(f"{organization_id}:{factory_code}")


def worker_uuid(factory_id: str, worker_code: str) -> uuid.UUID:
    """Deterministic worker ID: hash(factory_id:worker_code)."""
    return deterministic_uuid(f"{factory_id}:{worker_code}")


def session_uuid(worker_id: str, session_key: str) -> uuid.UUID:
    """Deterministic session ID: hash(worker_id:session_key)."""
    return deterministic_uuid(f"{worker_id}:{session_key}")


def stream_uuid(session_id: str, modality: str = "egocentric") -> uuid.UUID:
    """Deterministic stream ID: hash(session_id:modality)."""
    return deterministic_uuid(f"{session_id}:{modality}")


def clip_uuid(stream_id: str, clip_index: int) -> uuid.UUID:
    """Deterministic clip ID: hash(stream_id:clip_index)."""
    return deterministic_uuid(f"{stream_id}:{clip_index}")


def sync_uuids(
    organization_id: str,
    factory_code: str,
    worker_code: str,
    session_key: str,
    clip_index: int,
) -> tuple[uuid.UUID, uuid.UUID, uuid.UUID, uuid.UUID, uuid.UUID]:
    """Generate full hierarchy of deterministic UUIDs.

    Returns:
        (clip_id, stream_id, session_id, worker_id, factory_id)
    """
    fid = factory_uuid(organization_id, factory_code)
    wid = worker_uuid(str(fid), worker_code)
    sid = session_uuid(str(wid), session_key)
    stid = stream_uuid(str(sid))
    cid = clip_uuid(str(stid), clip_index)
    return cid, stid, sid, wid, fid
