# retoor <retoor@molodetz.nl>

from datetime import datetime, timezone

import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table, refresh_snapshot
from devplacepy.services.jobs import queue
from devplacepy.services.seo_meta import schedule_seo_meta
from devplacepy.utils import generate_uid, make_combined_slug

JSON = {"Accept": "application/json"}


def _db_user(name):
    refresh_snapshot()
    return get_table("users").find_one(username=name)


def _admin(seeded_db):
    key = _db_user("alice_test")["api_key"]
    s = requests.Session()
    s.headers.update({"X-API-KEY": key})
    return s


def _clear_seo_meta_jobs():
    refresh_snapshot()
    jobs = get_table("jobs")
    for row in list(jobs.find(kind="seo_meta")):
        jobs.delete(uid=row["uid"])


def _seed_post():
    uid = generate_uid()
    title = f"seometa {uid[:8]}"
    get_table("posts").insert(
        {
            "deleted_at": None,
            "deleted_by": None,
            "uid": uid,
            "user_uid": "",
            "slug": make_combined_slug(title, uid),
            "title": title,
            "content": "seo metadata subservice body text",
            "topic": "devlog",
            "project_uid": None,
            "image": None,
            "stars": 0,
            "created_at": datetime.now(timezone.utc).isoformat(),
        }
    )
    refresh_snapshot()
    return uid


def test_seo_meta_service_detail_json_requires_admin(app_server):
    r = requests.get(f"{BASE_URL}/admin/services/seo_meta/data", headers=JSON, allow_redirects=False)
    assert r.status_code in (302, 303, 401, 403)


def test_seo_meta_service_detail_json_shape(seeded_db):
    admin = _admin(seeded_db)
    r = admin.get(f"{BASE_URL}/admin/services/seo_meta/data", headers=JSON)
    assert r.status_code == 200, r.text[:300]
    service = r.json()["service"]
    assert service["name"] == "seo_meta"
    assert service["title"] == "SEO Metadata"
    metrics = service["metrics"]
    assert "stats" in metrics
    labels = {card["label"] for card in metrics["stats"]}
    assert "AI calls" in labels
    assert "Total cost" in labels


def test_seo_meta_service_config_exposes_backfill_fields(seeded_db):
    admin = _admin(seeded_db)
    r = admin.get(f"{BASE_URL}/admin/services/seo_meta/data", headers=JSON)
    assert r.status_code == 200, r.text[:300]
    field_keys = {field["key"] for field in r.json()["service"]["fields"]}
    assert "seo_meta_backfill_enabled" in field_keys
    assert "seo_meta_backfill_batch" in field_keys


def test_schedule_seo_meta_enqueues_job_visible_in_queue(app_server):
    try:
        target_uid = _seed_post()
        schedule_seo_meta("post", target_uid)
        refresh_snapshot()
        jobs = [
            job
            for job in queue.list_jobs(kind="seo_meta")
            if job["payload"].get("target_uid") == target_uid
        ]
        assert len(jobs) == 1
        job = jobs[0]
        assert job["kind"] == "seo_meta"
        assert job["payload"]["target_type"] == "post"
        assert job["owner_kind"] == "system"
    finally:
        _clear_seo_meta_jobs()


def test_schedule_seo_meta_does_not_double_enqueue(app_server):
    try:
        target_uid = _seed_post()
        schedule_seo_meta("post", target_uid)
        schedule_seo_meta("post", target_uid)
        refresh_snapshot()
        jobs = [
            job
            for job in queue.list_jobs(kind="seo_meta")
            if job["payload"].get("target_uid") == target_uid
        ]
        assert len(jobs) == 1
    finally:
        _clear_seo_meta_jobs()


def test_schedule_seo_meta_ignores_unknown_type(app_server):
    try:
        before = len(queue.list_jobs(kind="seo_meta"))
        schedule_seo_meta("nonsense", generate_uid())
        refresh_snapshot()
        after = len(queue.list_jobs(kind="seo_meta"))
        assert after == before
    finally:
        _clear_seo_meta_jobs()
