import os

import xxhash


def _sampling_payload(data: bytes) -> bytes:
    n = len(data)
    size_bytes = n.to_bytes(8, "little")
    if n < 3072:
        return size_bytes + data
    mid = (n - 1024) // 2
    return size_bytes + data[0:1024] + data[mid : mid + 1024] + data[-1024:]


def compute_media_content_hash(data: bytes, virtual: bool = False) -> str:
    payload = _sampling_payload(data)
    h = xxhash.xxh64(payload).hexdigest()
    return f"V{h}" if virtual else h


def compute_media_content_hash_from_file(path: str, virtual: bool = False) -> str:
    n = os.path.getsize(path)
    size_bytes = n.to_bytes(8, "little")
    with open(path, "rb") as f:
        if n < 3072:
            payload = size_bytes + f.read()
        else:
            first = f.read(1024)
            mid = (n - 1024) // 2
            f.seek(mid)
            middle = f.read(1024)
            f.seek(-1024, 2)
            last = f.read(1024)
            payload = size_bytes + first + middle + last
    h = xxhash.xxh64(payload).hexdigest()
    return f"V{h}" if virtual else h
