"""FC-2d-vii-c: importer sets artist_id, creates no artist tags."""

import pytest
from PIL import Image
from sqlalchemy import func, select

from backend.app.models import Artist, ImageRecord, ImportSettings, Tag, TagKind
from backend.app.services.importer import Importer
from backend.app.services.thumbnailer import Thumbnailer

pytestmark = pytest.mark.integration


@pytest.fixture
def import_layout(tmp_path):
    import_root = tmp_path / "import"
    images_root = tmp_path / "images"
    import_root.mkdir()
    images_root.mkdir()
    return import_root, images_root


@pytest.fixture
def importer(db_sync, import_layout):
    import_root, images_root = import_layout
    settings = db_sync.execute(
        select(ImportSettings).where(ImportSettings.id == 1)
    ).scalar_one()
    return Importer(
        session=db_sync, images_root=images_root, import_root=import_root,
        thumbnailer=Thumbnailer(images_root=images_root), settings=settings,
    )


def _img(path):
    path.parent.mkdir(parents=True, exist_ok=True)
    Image.new("RGB", (64, 64), (123, 200, 50)).save(path, "JPEG")


def test_folder_import_sets_artist_id_no_tag(importer, import_layout):
    import_root, _ = import_layout
    m = import_root / "Alice" / "pic.jpg"
    _img(m)
    r = importer.import_one(m)
    assert r.status == "imported"
    rec = importer.session.get(ImageRecord, r.image_id)
    artist = importer.session.execute(
        select(Artist).where(Artist.slug == "alice")
    ).scalar_one()
    assert rec.artist_id == artist.id
    n_artist_tags = importer.session.execute(
        select(func.count()).select_from(Tag).where(Tag.kind == TagKind.artist)
    ).scalar_one()
    assert n_artist_tags == 0
