from datetime import UTC, datetime

import pytest

from backend.app.models import (
    Artist,
    ImageProvenance,
    ImageRecord,
    Post,
    Source,
    Tag,
    TagKind,
)
from backend.app.models.tag import image_tag
from backend.app.services.artist_service import ArtistService

pytestmark = pytest.mark.integration


async def _fixture(db):
    artist = Artist(name="Nadia", slug="nadia")
    db.add(artist)
    await db.flush()
    src = Source(artist_id=artist.id, platform="web", url="http://x")
    db.add(src)
    await db.flush()
    post = Post(
        source_id=src.id, artist_id=artist.id, external_post_id="p1",
        post_date=datetime(2026, 3, 1, tzinfo=UTC),
    )
    db.add(post)
    await db.flush()
    img = ImageRecord(
        path="/images/a/1.jpg", sha256="a" + "0" * 63,
        size_bytes=1, mime="image/jpeg", width=4, height=8,
        origin="downloaded", integrity_status="unknown",
        # FC-2d-vii-c: provenance images also carry the canonical
        # artist_id (set by importer/migration); ArtistService reads it.
        artist_id=artist.id,
    )
    db.add(img)
    await db.flush()
    db.add(ImageProvenance(
        image_record_id=img.id, post_id=post.id, source_id=src.id))
    tag = Tag(name="forest", kind=TagKind.general)
    db.add(tag)
    await db.flush()
    await db.execute(image_tag.insert().values(
        image_record_id=img.id, tag_id=tag.id, source="manual"))
    await db.flush()
    return artist, src, img


@pytest.mark.asyncio
async def test_overview_aggregates(db):
    artist, src, img = await _fixture(db)
    svc = ArtistService(db)
    ov = await svc.overview("nadia")
    assert ov["name"] == "Nadia"
    assert ov["image_count"] == 1
    assert ov["date_range"]["min"].startswith("2026-03-01")
    assert ov["date_range"]["max"].startswith("2026-03-01")
    assert any(t["name"] == "forest" for t in ov["cooccurring_tags"])
    assert ov["sources"][0]["image_count"] == 1
    assert ov["activity"][0]["count"] == 1


@pytest.mark.asyncio
async def test_overview_unknown_slug_returns_none(db):
    svc = ArtistService(db)
    assert await svc.overview("ghost") is None


@pytest.mark.asyncio
async def test_paged_images(db):
    artist, src, img = await _fixture(db)
    svc = ArtistService(db)
    page = await svc.images("nadia", cursor=None, limit=10)
    assert page is not None
    assert len(page.images) == 1
    assert page.images[0]["thumbnail_url"].startswith("/images/thumbs/")


@pytest.mark.asyncio
async def test_paged_images_unknown_slug_none(db):
    svc = ArtistService(db)
    assert await svc.images("ghost", cursor=None, limit=10) is None


@pytest.mark.asyncio
async def test_overview_and_images_include_artist_id_only(db):
    # FC-2d-vii-c: a folder-style image has artist_id but no provenance.
    a = Artist(name="Solo", slug="solo")
    db.add(a)
    await db.flush()
    rec = ImageRecord(
        path="/images/s/1.jpg", sha256="s" + "0" * 63,
        size_bytes=1, mime="image/jpeg", width=1, height=1,
        origin="imported_filesystem", integrity_status="unknown",
        artist_id=a.id,
    )
    db.add(rec)
    await db.flush()

    svc = ArtistService(db)
    ov = await svc.overview("solo")
    assert ov["image_count"] == 1
    page = await svc.images("solo", cursor=None, limit=10)
    assert [i["id"] for i in page.images] == [rec.id]
