import pytest

from backend.app.models import ImageRecord, Tag, TagKind
from backend.app.models.tag import image_tag
from backend.app.services.tag_directory_service import TagDirectoryService

pytestmark = pytest.mark.integration


async def _img(db, i):
    r = ImageRecord(
        path=f"/images/td/{i}.jpg", sha256=f"d{i:063d}",
        size_bytes=1, mime="image/jpeg", width=1, height=1,
        origin="imported_filesystem", integrity_status="unknown",
    )
    db.add(r)
    await db.flush()
    return r


@pytest.mark.asyncio
async def test_directory_lists_tags_with_counts_and_previews(db):
    t = Tag(name="sunset", kind=TagKind.general)
    db.add(t)
    await db.flush()
    for i in range(4):
        img = await _img(db, i)
        await db.execute(image_tag.insert().values(
            image_record_id=img.id, tag_id=t.id, source="manual"))
    await db.flush()
    svc = TagDirectoryService(db)
    page = await svc.list_tags(kind=None, q=None, cursor=None, limit=10)
    card = next(c for c in page.cards if c["name"] == "sunset")
    assert card["image_count"] == 4
    assert len(card["preview_thumbnails"]) == 3
    assert card["preview_thumbnails"][0].startswith("/images/thumbs/")


@pytest.mark.asyncio
async def test_directory_fandom_counts_and_previews_via_characters(db):
    # A fandom card aggregates images of its characters (Tag.fandom_id), not
    # just images tagged with the fandom directly. DISTINCT: an image carrying
    # both the fandom and one of its characters counts once.
    fandom = Tag(name="Bleach", kind=TagKind.fandom)
    db.add(fandom)
    await db.flush()
    char = Tag(name="Ichigo", kind=TagKind.character, fandom_id=fandom.id)
    db.add(char)
    await db.flush()
    # A SECOND, unrelated fandom + character + image. The count for "Bleach"
    # must NOT pick this up — guards against the count's fandom leg failing to
    # correlate the outer tag and counting EVERY fandom-character globally
    # (which inflates every card to the same number).
    other_fandom = Tag(name="Naruto", kind=TagKind.fandom)
    db.add(other_fandom)
    await db.flush()
    other_char = Tag(name="Sasuke", kind=TagKind.character, fandom_id=other_fandom.id)
    db.add(other_char)
    await db.flush()
    # img0: character only; img1: fandom direct; img2: BOTH (dedup → counts once)
    img0, img1, img2 = await _img(db, 0), await _img(db, 1), await _img(db, 2)
    other_img = await _img(db, 3)
    await db.execute(image_tag.insert().values([
        {"image_record_id": img0.id, "tag_id": char.id, "source": "manual"},
        {"image_record_id": img1.id, "tag_id": fandom.id, "source": "manual"},
        {"image_record_id": img2.id, "tag_id": char.id, "source": "manual"},
        {"image_record_id": img2.id, "tag_id": fandom.id, "source": "manual"},
        {"image_record_id": other_img.id, "tag_id": other_char.id, "source": "manual"},
    ]))
    await db.flush()
    svc = TagDirectoryService(db)
    page = await svc.list_tags(kind="fandom", q=None, cursor=None, limit=10)
    card = next(c for c in page.cards if c["name"] == "Bleach")
    assert card["image_count"] == 3  # NOT 4 — Naruto's image must be excluded
    assert len(card["preview_thumbnails"]) == 3
    # The unrelated fandom counts only its own one image.
    other = next(c for c in page.cards if c["name"] == "Naruto")
    assert other["image_count"] == 1


@pytest.mark.asyncio
async def test_directory_kind_filter_and_search(db):
    db.add_all([
        Tag(name="artist_a", kind=TagKind.artist),
        Tag(name="char_b", kind=TagKind.character),
        Tag(name="char_zoom", kind=TagKind.character),
    ])
    await db.flush()
    svc = TagDirectoryService(db)
    only_char = await svc.list_tags(kind="character", q=None, cursor=None, limit=10)
    assert {c["name"] for c in only_char.cards} == {"char_b", "char_zoom"}
    searched = await svc.list_tags(kind=None, q="zoom", cursor=None, limit=10)
    assert {c["name"] for c in searched.cards} == {"char_zoom"}


@pytest.mark.asyncio
async def test_directory_cursor_pagination(db):
    for i in range(5):
        db.add(Tag(name=f"t{i:02d}", kind=TagKind.general))
    await db.flush()
    svc = TagDirectoryService(db)
    first = await svc.list_tags(kind=None, q=None, cursor=None, limit=2)
    assert len(first.cards) == 2
    assert first.next_cursor is not None
    second = await svc.list_tags(kind=None, q=None, cursor=first.next_cursor, limit=2)
    assert len(second.cards) == 2
    assert {c["id"] for c in first.cards}.isdisjoint({c["id"] for c in second.cards})


@pytest.mark.asyncio
async def test_directory_rejects_bad_limit(db):
    svc = TagDirectoryService(db)
    with pytest.raises(ValueError):
        await svc.list_tags(kind=None, q=None, cursor=None, limit=0)
