"""Invisible watermark extraction.

Uses DWT + DCT extraction via the ``imwatermark`` package when available.
Falls back gracefully so that verification still works without it.
"""

from __future__ import annotations

import io
import logging

import numpy as np
from PIL import Image

logger = logging.getLogger(__name__)

_WATERMARK_LENGTH_BITS = 256


def _try_import_imwatermark():
    """Attempt to import imwatermark; return the WatermarkDecoder or None."""
    try:
        from imwatermark import WatermarkDecoder  # type: ignore[import-untyped]
        return WatermarkDecoder
    except ImportError:
        return None


def extract_watermark(image_bytes: bytes) -> bytes:
    """Extract an embedded invisible watermark from an image.

    The watermark is expected to be a 256-bit payload embedded using
    DWT + DCT steganography (the scheme used by ``imwatermark``).

    Returns the raw watermark bytes (32 bytes for a 256-bit payload).
    Returns empty bytes if extraction is unavailable or fails.
    """
    WatermarkDecoder = _try_import_imwatermark()

    if WatermarkDecoder is None:
        logger.info(
            "imwatermark is not installed — skipping watermark extraction. "
            "Install with: pip install tectra-verify[watermark]"
        )
        return b""

    try:
        image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
        bgr_array = np.array(image)[:, :, ::-1]

        decoder = WatermarkDecoder("bytes", _WATERMARK_LENGTH_BITS)
        payload: bytes = decoder.decode(bgr_array, method="dwtDct")
        return payload
    except Exception:
        logger.warning("Watermark extraction failed", exc_info=True)
        return b""
