import asyncio
from pathlib import Path

from services import emby_tasks
from services import music_covers as music_service


def run(coro):
    return asyncio.run(coro)


def test_describe_tasks_marks_navidrome_tasks_unavailable_without_music_root(tmp_path, monkeypatch):
    monkeypatch.setattr(music_service, "MUSIC_ROOT", tmp_path / "missing-music-root")
    settings = emby_tasks.default_settings()

    tasks = {task["id"]: task for task in emby_tasks.describe_tasks(settings)}

    assert tasks["navidrome_file_cleanup"]["supports_run"] is False
    assert tasks["navidrome_cover_backfill"]["requires"] == "music_root"


def test_navidrome_file_cleanup_preview_and_apply(tmp_path, monkeypatch):
    music_root = tmp_path / "music"
    album = music_root / "Boards of Canada" / "Music Has the Right to Children"
    album.mkdir(parents=True)
    (album / "cover.jpg").write_bytes(b"cover")
    (album / "booklet.pdf").write_bytes(b"pdf")
    (album / "notes.nfo").write_text("extra", encoding="utf-8")

    monkeypatch.setattr(music_service, "MUSIC_ROOT", music_root)
    monkeypatch.setattr(emby_tasks, "STATE_FILE", tmp_path / "tasks-state.json")

    settings = emby_tasks.default_settings()

    preview = run(emby_tasks.run_task("navidrome_file_cleanup", client=None, settings=settings, dry_run=True))
    assert preview["ok"] is True
    assert preview["matched_count"] == 2
    assert "would be removed" in preview["message"]
    assert (album / "booklet.pdf").exists()
    assert (album / "notes.nfo").exists()

    applied = run(emby_tasks.run_task("navidrome_file_cleanup", client=None, settings=settings, dry_run=False))
    assert applied["ok"] is True
    assert applied["removed_count"] == 2
    assert not (album / "booklet.pdf").exists()
    assert not (album / "notes.nfo").exists()


def test_record_run_persists_task_status(tmp_path, monkeypatch):
    monkeypatch.setattr(emby_tasks, "STATE_FILE", tmp_path / "tasks-state.json")

    entry = emby_tasks.record_run("navidrome_file_cleanup", {"ok": True, "message": "done"}, automated=True)
    state = emby_tasks.load_state()

    assert entry["last_status"] == "ok"
    assert state["tasks"]["navidrome_file_cleanup"]["last_result"]["message"] == "done"
    assert "last_automation_week" in state["tasks"]["navidrome_file_cleanup"]
