from __future__ import annotations

import base64
from typing import Any

from PIL import Image


def decode_document_extractor_image_payload(image_payload: Any) -> bytes:
    """Decode one screenshot payload returned by DSS document extraction APIs."""

    if isinstance(image_payload, bytes):
        return image_payload
    if isinstance(image_payload, str):
        return base64.b64decode(image_payload)
    raise TypeError(f"Unsupported screenshot payload type: {type(image_payload)}")


def resize_image_with_ratio(image: Image.Image) -> Image.Image:
    """Resize an image to the configured bounding box while preserving aspect ratio."""

    width, height = image.size
    # Define bounding box depending on orientation.
    if width >= height:
        # landscape
        max_w, max_h = 720, 405
    else:
        # portrait
        max_w, max_h = 405, 720

    # Compute scale to fit inside that box while keeping aspect ratio.
    scale = min(max_w / width, max_h / height, 1.0)  # Don't upscale past 100%.
    new_size = (int(round(width * scale)), int(round(height * scale)))
    return image.resize(new_size, Image.LANCZOS)


def structured_document_chunks_to_text(chunks: list[dict[str, Any]]) -> str:
    """Flatten DSS structured extraction chunks into a readable text blob."""

    lines: list[str] = []
    for chunk in chunks:
        text = (chunk.get("text") or "").strip()
        if not text:
            continue
        outline = [part for part in chunk.get("outline", []) if part]
        if outline:
            lines.append(" > ".join(outline))
        lines.append(text)
        lines.append("")
    return "\n".join(lines).strip()
