from __future__ import annotations

import base64
from pathlib import Path


def decode_base64_image(raw_value: str) -> bytes:
    token = str(raw_value or "").strip()
    if not token:
        raise ValueError("event_image base64 is empty.")
    try:
        return base64.b64decode(token, validate=True)
    except Exception as exc:
        raise ValueError("Invalid base64 payload in event_image.") from exc


def detect_image_extension(image_bytes: bytes) -> str:
    if image_bytes.startswith(b"\xff\xd8\xff"):
        return ".jpg"
    if image_bytes.startswith(b"\x89PNG\r\n\x1a\n"):
        return ".png"
    if image_bytes.startswith(b"GIF87a") or image_bytes.startswith(b"GIF89a"):
        return ".gif"
    return ".bin"


def write_image_bytes(path: Path, image_bytes: bytes, *, overwrite: bool) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.exists() and not overwrite:
        raise FileExistsError(f"Output file already exists: {path}")
    path.write_bytes(image_bytes)
