"""Regression guard: Kling i2v must inject BOTH the start frame and the
end/tail frame into the provider submit body.

For months the end (tail) frame was silently dropped from every Kling i2v
request — only the start frame was sent — which made Kling's start+end-frame
interpolation (the researched best lever for shot control) unusable and got the
protocol shelved. The wiring is correct on current main
(`KlingAdapter._build_generation_body` sets `body["end_image_url"]` from
`payload.image_tail`), but nothing tested the body builder, so it could silently
regress the same way. This pins it.
"""

from __future__ import annotations

import base64

import pytest

from recoil.execution.providers.base import UnifiedVideoPayload
from recoil.execution.providers.kling import KlingAdapter

# Mirror the live dispatch_payload shape: start + end frames arrive as raw
# base64 strings (dispatch_payload.py sets payload["image_tail"] = <b64 str>).
_START_B64 = base64.b64encode(b"START_FRAME_PIXELS").decode()
_END_B64 = base64.b64encode(b"END_FRAME_PIXELS").decode()


@pytest.fixture
def adapter(monkeypatch):
    monkeypatch.setenv("FAL_KEY", "test-key")
    return KlingAdapter()


def test_kling_i2v_injects_both_start_and_end_frames(adapter):
    payload = UnifiedVideoPayload(
        prompt="interpolate start to end",
        image=_START_B64,
        image_tail=_END_B64,
        model_id="kling-v3-i2v",
    )

    req = adapter.build_submit(payload, "standard")

    # Start frame present under the i2v frame key.
    assert req.body["image_url"].startswith("data:image/png;base64,")
    # END frame present — the historical silent-drop bug.
    assert "end_image_url" in req.body, "Kling i2v dropped the end/tail frame"
    assert req.body["end_image_url"].endswith(_END_B64)
    # Distinct frames (start != end).
    assert req.body["image_url"] != req.body["end_image_url"]


def test_kling_i2v_without_tail_omits_end_frame(adapter):
    # Control: a start-only i2v shot must NOT carry an end_image_url (proves the
    # assertion above is driven by image_tail, not always-present).
    payload = UnifiedVideoPayload(
        prompt="single keyframe drive",
        image=_START_B64,
        model_id="kling-v3-i2v",
    )

    req = adapter.build_submit(payload, "standard")

    assert req.body["image_url"].startswith("data:image/png;base64,")
    assert "end_image_url" not in req.body
