"""
Resize-robust watermarking for clawID.

Named "fourier_mellin" for API stability (the module was originally planned as a
DFT log-polar scheme), but the implementation uses DWT-QIM with a larger delta
that is calibrated for resize robustness.

Why DFT log-polar does not work for uint8 images:
  Modifying an individual DFT coefficient by ΔM causes per-pixel changes of
  only 2·ΔM / N² ≈ 2·2000 / 262144 ≈ 0.015 per pixel — far below the uint8
  quantization step of 0.5. The watermark is erased when the image is saved as
  uint8 regardless of delta.

Why DWT-QIM with larger delta does work:
  Each LL2 Haar coefficient represents the sum of a 4×4 pixel block, so a
  coefficient change of delta propagates to visible (~delta/16) per-pixel deltas
  that survive uint8 quantization.
  After an 80% resize+renormalize round-trip the LL2 coefficients drift by
  std ≈ 12.5 units (empirical, 512×512 random images). QIM tolerance = delta/4,
  so delta=192 gives tolerance=48 >> p95 drift=20.5 → essentially zero bit errors.

Comparison to the 'qim' algorithm:
  • qim  (delta=32):  PSNR ≈ 51 dB — imperceptible, robust to JPEG but NOT resize
  • fm   (delta=192): PSNR ≈ 36 dB — slight quality reduction, robust to ±35% resize
                      AND JPEG compression
"""

# Re-export the DWT-QIM primitives with resize-robust parameters so that
# detect.py / embed.py can import consistently from this module.

from .dwt_qim import embed_bits as _qim_embed, extract_bits as _qim_extract
from typing import List
from PIL import Image

# ── constants (must match between embed and detect) ──────────────────────────

DELTA = 192.0    # Larger QIM step → tolerance 48 >> resize drift std 12.5
REPEAT = 3       # Majority-vote repetition (same as QIM mode)

# MAX_SCALE_SHIFT is kept for API compatibility only; not used here.
MAX_SCALE_SHIFT = 0


def embed_bits(
    image: Image.Image,
    bits: List[int],
    delta: float = DELTA,
    repeat: int = REPEAT,
) -> Image.Image:
    """
    Embed bits using DWT-QIM with delta=192 (resize-robust).

    Identical interface to dwt_qim.embed_bits; uses a larger delta so the
    watermark survives ±35% resize as well as JPEG compression.
    """
    return _qim_embed(image, bits, delta=delta, repeat=repeat)


def extract_bits(
    image: Image.Image,
    n_bits: int,
    delta: float = DELTA,
    repeat: int = REPEAT,
    shift: int = 0,   # kept for API compatibility; ignored
) -> List[int]:
    """
    Extract bits using DWT-QIM with delta=192.

    The `shift` parameter is accepted for API compatibility but is not used
    (DWT-QIM does not require a shift search for scale compensation).
    """
    return _qim_extract(image, n_bits, delta=delta, repeat=repeat)
