"""
Platform-Calibrated DCT Presets (v4.4.0)

Pre-tuned DCT embedding parameters for social media platforms. Each platform
recompresses uploaded images differently — these presets bake in the known
parameters so payloads survive the round-trip.

Usage::

    from stegasoo.platform_presets import get_preset, PLATFORMS

    preset = get_preset("telegram")
    # Use preset.quant_step, preset.jpeg_quality, etc. in DCT encode

Preset parameters were derived from empirical testing. Platform compression
behavior can change without notice — use ``pre_verify_survival()`` to confirm
payloads survive before relying on a preset.
"""

from __future__ import annotations

from dataclasses import dataclass


@dataclass(frozen=True)
class PlatformPreset:
    """Tuned DCT parameters for a specific platform."""

    name: str
    jpeg_quality: int  # Platform's recompression quality
    max_dimension: int  # Max width/height before platform resizes
    quant_step: int  # QIM quantization step (higher = more robust)
    embed_start: int  # Start index into EMBED_POSITIONS (skip low-freq)
    embed_end: int  # End index into EMBED_POSITIONS (skip high-freq)
    recompress_quality: int  # Quality to simulate platform recompression for pre-verify
    notes: str = ""


# Platform presets — derived from empirical testing of each platform's
# image processing pipeline. These WILL change as platforms update.
# Last verified: 2026-03-25

PRESETS: dict[str, PlatformPreset] = {
    "telegram": PlatformPreset(
        name="Telegram",
        jpeg_quality=82,
        max_dimension=2560,
        quant_step=35,
        embed_start=4,
        embed_end=16,
        recompress_quality=80,
        notes="~81KB max embeddable. Moderate recompression.",
    ),
    "discord": PlatformPreset(
        name="Discord",
        jpeg_quality=85,
        max_dimension=4096,
        quant_step=30,
        embed_start=4,
        embed_end=18,
        recompress_quality=83,
        notes="Varies with Nitro. Non-Nitro users get more aggressive compression.",
    ),
    "signal": PlatformPreset(
        name="Signal",
        jpeg_quality=80,
        max_dimension=2048,
        quant_step=40,
        embed_start=5,
        embed_end=15,
        recompress_quality=78,
        notes="Aggressive recompression. Use smaller payloads for reliability.",
    ),
    "whatsapp": PlatformPreset(
        name="WhatsApp",
        jpeg_quality=70,
        max_dimension=1600,
        quant_step=50,
        embed_start=5,
        embed_end=14,
        recompress_quality=68,
        notes="Most lossy. Capacity is significantly reduced.",
    ),
}

PLATFORMS = sorted(PRESETS.keys())


def get_preset(platform: str) -> PlatformPreset:
    """Get the preset for a platform.

    Args:
        platform: Platform name (telegram, discord, signal, whatsapp).

    Returns:
        PlatformPreset with tuned DCT parameters.

    Raises:
        ValueError: If platform is not recognized.
    """
    key = platform.lower()
    if key not in PRESETS:
        available = ", ".join(PLATFORMS)
        raise ValueError(f"Unknown platform '{platform}'. Available: {available}")
    return PRESETS[key]


def get_embed_positions(preset: PlatformPreset) -> list[tuple[int, int]]:
    """Get the embed positions for a preset.

    Args:
        preset: Platform preset.

    Returns:
        List of (row, col) DCT coefficient positions.
    """
    from .dct_steganography import EMBED_POSITIONS

    return EMBED_POSITIONS[preset.embed_start : preset.embed_end]


def pre_verify_survival(
    stego_image: bytes,
    seed: bytes,
    preset: PlatformPreset,
) -> bool:
    """Verify that a payload survives simulated platform recompression.

    Encodes → recompresses at platform quality → attempts extraction.
    If extraction succeeds, the payload should survive the real platform.

    Args:
        stego_image: The stego JPEG image bytes (already encoded).
        seed: The same seed used for encoding.
        preset: Platform preset to simulate.

    Returns:
        True if payload survived simulated recompression.
    """
    import io

    from PIL import Image

    from .dct_steganography import extract_from_dct

    # Simulate platform recompression
    img = Image.open(io.BytesIO(stego_image))

    # Resize if over max dimension
    w, h = img.size
    if max(w, h) > preset.max_dimension:
        scale = preset.max_dimension / max(w, h)
        new_size = (int(w * scale), int(h * scale))
        img = img.resize(new_size, Image.LANCZOS)

    # Recompress at platform quality
    buf = io.BytesIO()
    if img.mode != "RGB":
        img = img.convert("RGB")
    img.save(buf, format="JPEG", quality=preset.recompress_quality)
    img.close()
    recompressed = buf.getvalue()

    # Try extraction
    try:
        result = extract_from_dct(recompressed, seed)
        return result is not None and len(result) > 0
    except Exception:
        return False
