"""seedream 요청에 **화면 비율이 실린다** (2026-09-19 S72sh43).

`_SeedreamCineClient.generate_image(aspect_ratio="16:9")` 가 비율을 받기만 하고
OpenRouter 로 보내는 body 에 안 실어서, seedream 기본값 **정사각형(2048×2048)**
이 16:9 원본의 최종본이 됐다.

잰다: 실제로 나가는 HTTP body — 조립 자리가 아니라 끝점이다. urlopen 만
막고 그 위는 전부 production 코드다.
"""
from __future__ import annotations

import base64
import io
import json

import pytest


def _png_bytes():
    from PIL import Image

    buf = io.BytesIO()
    Image.new("RGB", (4, 4), (10, 20, 30)).save(buf, format="PNG")
    return buf.getvalue()


class _Resp:
    def __init__(self, payload):
        self._b = json.dumps(payload).encode("utf-8")

    def read(self):
        return self._b

    def __enter__(self):
        return self

    def __exit__(self, *a):
        return False


@pytest.fixture
def sent(monkeypatch):
    """나가는 요청 body 를 모은다 — 바깥은 부르지 않는다."""
    from app.core import config, image_call_budget
    from app.modules.llm import llm_logger

    bodies = []
    png = _png_bytes()

    def fake_urlopen(req, timeout=None):
        bodies.append(json.loads(req.data.decode("utf-8")))
        return _Resp({"data": [{"b64_json": base64.b64encode(png).decode()}]})

    monkeypatch.setattr(config.settings, "openrouter_api_key", "SAMPLE-KEY",
                        raising=False)
    monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)
    monkeypatch.setattr(image_call_budget, "reserve_current_call",
                        lambda **k: None)
    monkeypatch.setattr(llm_logger, "log_llm_call", lambda **k: None)
    return bodies


def test_seedream_cine_client_sends_the_aspect_ratio(sent):
    from app.modules.pipeline.cine_provider import build_cine_client

    client = build_cine_client("seedream")
    png, _ms = client.generate_image(
        "SAMPLE", labeled_references=[("SOURCE STILL", _png_bytes())],
        aspect_ratio="16:9")
    assert png
    assert len(sent) == 1
    assert sent[0]["aspect_ratio"] == "16:9"


def test_cine_default_is_the_still_ratio(sent):
    """cine 변환 호출부는 비율을 안 넘긴다 — 슬롯 기본값(16:9)이 실려야 한다."""
    from app.modules.pipeline.cine_provider import build_cine_client

    build_cine_client("seedream").generate_image(
        "SAMPLE", labeled_references=[("SOURCE STILL", _png_bytes())])
    assert sent[0]["aspect_ratio"] == "16:9"


def test_marker_map_callers_are_byte_identical(sent, tmp_path):
    """비율을 안 주는 마커 맵 호출은 body 에 그 칸이 **없다**(예전과 같다)."""
    from app.modules.pipeline.marker_map_engine import (
        draw_marker_map_via_model,
    )

    ref = tmp_path / "base.png"
    ref.write_bytes(_png_bytes())
    draw_marker_map_via_model(
        model="bytedance-seed/seedream-5-0-pro", prompt="SAMPLE",
        ref_paths=[ref])
    assert set(sent[0]) == {"model", "prompt", "input_references"}


def test_old_square_records_are_not_reused():
    """요청 모양이 바뀌었으니 옛 seedream 변환 지문은 지금 것과 달라야 한다."""
    from app.modules.pipeline.cine_provider import cine_provider_identity
    from app.modules.pipeline.cine_transform import cine_fingerprint_v2

    now = cine_provider_identity("seedream")
    old = {**now, "endpoint": "openrouter/images"}
    kw = dict(prompt="SAMPLE", stem_content_hash="SAMPLE", sel_bytes=b"S")
    assert (cine_fingerprint_v2(identity=now, **kw)
            != cine_fingerprint_v2(identity=old, **kw))
