"""embed_image (embed-only) / backfill task tests. The pure _is_video helper
is a unit test; the DB-touching backfill query is an integration test with
monkeypatched dispatch."""

from pathlib import Path

import pytest

from backend.app.tasks.ml import _is_video


def test_is_video():
    assert _is_video(Path("a.mp4")) is True
    assert _is_video(Path("a.MKV")) is True
    assert _is_video(Path("a.jpg")) is False


@pytest.mark.integration
@pytest.mark.asyncio
async def test_backfill_enqueues_missing(db, monkeypatch):
    from backend.app.models import ImageRecord
    from backend.app.tasks import ml as ml_tasks

    calls = []
    monkeypatch.setattr(
        ml_tasks.embed_image, "delay", lambda image_id: calls.append(image_id)
    )

    img = ImageRecord(
        path="/images/n.jpg", sha256="n" * 64, size_bytes=1,
        mime="image/jpeg", width=1, height=1,
        origin="imported_filesystem", integrity_status="unknown",
        siglip_embedding=None,
    )
    db.add(img)
    await db.commit()

    count = ml_tasks.backfill()
    assert count >= 1
    assert img.id in calls


@pytest.mark.integration
@pytest.mark.asyncio
async def test_backfill_respects_cpu_embed_toggle(db, monkeypatch):
    """B3: with cpu_embed_enabled off (agent-equipped stack, no ml-worker),
    the CPU backfill is a no-op — the GPU 'embed' backfill owns whole-image
    embeds there. Same gate the import hooks consult before dispatching."""
    from sqlalchemy import update

    from backend.app.models import ImageRecord, MLSettings
    from backend.app.tasks import ml as ml_tasks

    calls = []
    monkeypatch.setattr(
        ml_tasks.embed_image, "delay", lambda image_id: calls.append(image_id)
    )
    db.add(ImageRecord(
        path="/images/o.jpg", sha256="o" * 64, size_bytes=1,
        mime="image/jpeg", width=1, height=1,
        origin="imported_filesystem", integrity_status="unknown",
        siglip_embedding=None,
    ))
    await db.execute(
        update(MLSettings).where(MLSettings.id == 1)
        .values(cpu_embed_enabled=False)
    )
    await db.commit()

    assert ml_tasks.cpu_embed_enabled() is False
    assert ml_tasks.backfill() == 0
    assert calls == []
