"""app.widgets.photos -- unit-level, no HTTP: constructs Widget/
PhotoWidgetConfig rows directly and monkeypatches the Immich-facing
calls (list_assets/fetch_source_and_faces/immich_client_for) rather than
standing up a fake Immich server, since this module's own logic (what it
does with whatever Immich returns) is what's under test, not Immich's
API shape -- already covered by ImmichClient's own tests if any, and by
this suite's HTTP-level permission-boundary tests elsewhere."""

from __future__ import annotations

import time

from PIL import Image

from app import widgets
from app.db import widget_locked
from app.models import Frame, PhotoWidgetConfig, Widget

_ASSETS = [{"id": "asset-1"}, {"id": "asset-2"}, {"id": "asset-3"}]


def _make_widget(db_session, album_id="album-1") -> tuple[Frame, Widget]:
    frame = db_session.get(Frame, 1)
    widget = Widget(frame_id=frame.id, widget_type="photos", x=0, y=0, w=8, h=5,
                    sort_order=0, created_at=time.time())
    db_session.add(widget)
    db_session.flush()
    db_session.add(PhotoWidgetConfig(widget_id=widget.id, album_id=album_id, queue_target_len=5))
    db_session.commit()
    return frame, widget


def test_render_unconfigured_widget_returns_correctly_sized_placeholder(db_session):
    frame, widget = _make_widget(db_session, album_id="")
    img = widgets.photos.render(db_session, frame, widget, 400, 300)
    assert img.size == (400, 300)
    assert img.mode == "RGB"


def test_render_configured_widget_composes_a_photo(db_session, monkeypatch):
    frame, widget = _make_widget(db_session)

    monkeypatch.setattr(widgets.photos, "immich_client_for", lambda frame: object())
    monkeypatch.setattr(widgets.photos, "list_assets", lambda client, album_id: _ASSETS)
    source = Image.new("RGB", (100, 80), (10, 20, 30))
    monkeypatch.setattr(widgets.photos, "fetch_source_and_faces", lambda client, mode, asset_id: (source, None))

    img = widgets.photos.render(db_session, frame, widget, 400, 300)
    assert img.size == (400, 300)

    cfg = db_session.get(PhotoWidgetConfig, widget.id)
    assert cfg.current_asset_id == "asset-1"  # get_current picked the first asset


def test_render_falls_back_to_placeholder_on_immich_failure(db_session, monkeypatch):
    from fastapi import HTTPException

    frame, widget = _make_widget(db_session)

    def _raise(client, album_id):
        raise HTTPException(502, "Could not reach Immich")

    monkeypatch.setattr(widgets.photos, "immich_client_for", lambda frame: object())
    monkeypatch.setattr(widgets.photos, "list_assets", _raise)

    img = widgets.photos.render(db_session, frame, widget, 400, 300)
    assert img.size == (400, 300)  # placeholder, not a crash


def test_advance_action_moves_to_next_photo(db_session, monkeypatch):
    frame, widget = _make_widget(db_session)
    monkeypatch.setattr(widgets.photos, "immich_client_for", lambda frame: object())
    monkeypatch.setattr(widgets.photos, "list_assets", lambda client, album_id: _ASSETS)

    with widget_locked(db_session, frame.id, widget.id) as (_, _, cfg):
        cfg.current_asset_id = "asset-1"

    widgets.photos.ACTIONS["advance"](db_session, frame, widget)

    cfg = db_session.get(PhotoWidgetConfig, widget.id)
    assert cfg.current_asset_id != "asset-1"
    assert cfg.history == ["asset-1"]


def test_back_action_undoes_advance(db_session, monkeypatch):
    frame, widget = _make_widget(db_session)
    monkeypatch.setattr(widgets.photos, "immich_client_for", lambda frame: object())
    monkeypatch.setattr(widgets.photos, "list_assets", lambda client, album_id: _ASSETS)

    # advance_forced only pushes the *previous* current photo onto history
    # -- the very first advance from an empty current_asset_id has nothing
    # to push, so a second advance is needed before there's anything for
    # "back" to undo.
    widgets.photos.ACTIONS["advance"](db_session, frame, widget)
    first = db_session.get(PhotoWidgetConfig, widget.id).current_asset_id
    widgets.photos.ACTIONS["advance"](db_session, frame, widget)
    second = db_session.get(PhotoWidgetConfig, widget.id).current_asset_id
    assert second != first

    widgets.photos.ACTIONS["back"](db_session, frame, widget)
    cfg = db_session.get(PhotoWidgetConfig, widget.id)
    assert cfg.current_asset_id == first


def test_advance_action_is_a_no_op_when_unconfigured(db_session):
    frame, widget = _make_widget(db_session, album_id="")
    widgets.photos.ACTIONS["advance"](db_session, frame, widget)  # must not raise
    cfg = db_session.get(PhotoWidgetConfig, widget.id)
    assert cfg.current_asset_id == ""


def test_advance_uses_the_frame_stats_counter_not_the_widget_config():
    """advance_forced's frame/stats split (see app/photo_queue.py) means
    stats_photos_displayed should land on the Frame row, never on
    PhotoWidgetConfig (which has no such column at all)."""
    assert not hasattr(PhotoWidgetConfig, "stats_photos_displayed")
