import pytest
from sqlalchemy import select
from sqlalchemy.exc import IntegrityError

from backend.app.models import ImageRecord, TagKind
from backend.app.models.series_chapter import SeriesChapter
from backend.app.models.series_page import SeriesPage
from backend.app.services.tag_service import TagService

pytestmark = pytest.mark.integration

_SEQ = 0


async def _img(db):
    global _SEQ
    _SEQ += 1
    rec = ImageRecord(
        path=f"/tmp/fc_sp_{_SEQ}.png", sha256=f"{_SEQ:064d}",
        size_bytes=1, mime="image/png", origin="uploaded",
    )
    db.add(rec)
    await db.flush()
    return rec.id


@pytest.mark.asyncio
async def test_series_page_roundtrip_and_unique_image(db):
    s = await TagService(db).find_or_create("Vol1", TagKind.series)
    i1 = await _img(db)
    db.add(SeriesPage(series_tag_id=s.id, image_id=i1, page_number=1))
    await db.flush()
    got = await db.scalar(
        select(SeriesPage.page_number).where(SeriesPage.image_id == i1)
    )
    assert got == 1
    # UNIQUE image_id: same image can't be a page twice (any series).
    s2 = await TagService(db).find_or_create("Vol2", TagKind.series)
    db.add(SeriesPage(series_tag_id=s2.id, image_id=i1, page_number=1))
    with pytest.raises(IntegrityError):
        await db.flush()


@pytest.mark.asyncio
async def test_chapter_divider_anchor_is_unique(db):
    # A chapter divider anchors to the page that begins it; one divider per page.
    s = await TagService(db).find_or_create("Vol3", TagKind.series)
    i1 = await _img(db)
    p = SeriesPage(series_tag_id=s.id, image_id=i1, page_number=1)
    db.add(p)
    await db.flush()
    db.add(SeriesChapter(series_tag_id=s.id, anchor_page_id=p.id))
    await db.flush()
    db.add(SeriesChapter(series_tag_id=s.id, anchor_page_id=p.id))
    with pytest.raises(IntegrityError):
        await db.flush()
