"""Brief sheet 4: photographer mode is a switch (and kills its link), AI themes are ticked per school."""
import uuid

import pytest

import ia
from conftest import DEMO_CODE

THEMES = [{"id": "3", "name": "Scientist", "name_fr": "Scientifique"},
          {"id": "78", "name": "Firefighter", "name_fr": "Pompier"},
          {"id": "800", "name": "Astronaut", "name_fr": "Astronaute"}]


@pytest.fixture
def themes(monkeypatch):
    async def fake():
        return THEMES
    monkeypatch.setattr(ia, "fetch_themes", fake)


async def _ids(client, **kw):
    r = await client.get("/api/portal/themes", params=kw)
    return [t["id"] for t in r.json()["themes"]]


async def test_a_school_that_never_chose_offers_every_theme(client, admin_headers, themes):
    listed = (await client.get("/api/admin/ai-themes", headers=admin_headers)).json()["themes"]
    assert [t["id"] for t in listed] == ["3", "78", "800"] and all(t["enabled"] for t in listed)
    assert await _ids(client, code=DEMO_CODE) == ["3", "78", "800"]


async def test_only_ticked_themes_reach_the_family_and_at_once(client, admin_headers, themes):
    r = await client.put("/api/admin/ai-themes", json={"enabled": ["78", "800", "999"]}, headers=admin_headers)
    assert r.status_code == 200
    assert {t["id"]: t["enabled"] for t in r.json()["themes"]} == {"3": False, "78": True, "800": True}   # 999 ignored
    assert await _ids(client, code=DEMO_CODE) == ["78", "800"]
    await client.put("/api/admin/ai-themes", json={"enabled": []}, headers=admin_headers)
    assert await _ids(client, code=DEMO_CODE) == []
    await client.put("/api/admin/ai-themes", json={"enabled": ["3"]}, headers=admin_headers)
    assert await _ids(client, code=DEMO_CODE) == ["3"]
    # restore for the other tests
    await client.put("/api/admin/settings", json={"settings": {"ai_themes": "all"}}, headers=admin_headers)


async def test_themes_are_per_school_and_a_theme_added_later_starts_off(client, admin_headers, other_admin_headers,
                                                                        themes, monkeypatch):
    await client.put("/api/admin/ai-themes", json={"enabled": ["3", "78", "800"]}, headers=admin_headers)
    newcomer = {"id": "1000", "name": "Teacher", "name_fr": "Enseignant"}

    async def more():
        return THEMES + [newcomer]
    monkeypatch.setattr(ia, "fetch_themes", more)
    listed = {t["id"]: t["enabled"] for t in (await client.get("/api/admin/ai-themes", headers=admin_headers)).json()["themes"]}
    assert listed["1000"] is False and listed["3"] is True            # added by StoryFace: unticked until the admin ticks it
    other = {t["id"]: t["enabled"] for t in (await client.get("/api/admin/ai-themes", headers=other_admin_headers)).json()["themes"]}
    assert all(other.values())                                       # the other school never chose
    await client.put("/api/admin/settings", json={"settings": {"ai_themes": "all"}}, headers=admin_headers)


async def test_the_theme_choice_is_the_admins_and_is_journaled(client, admin_headers, operator_headers, themes):
    assert (await client.get("/api/admin/ai-themes", headers=operator_headers)).status_code == 403
    assert (await client.put("/api/admin/ai-themes", json={"enabled": []}, headers=operator_headers)).status_code == 403
    await client.put("/api/admin/ai-themes", json={"enabled": ["3"]}, headers=admin_headers)
    ev = (await client.get("/api/admin/audit?action=ai_themes", headers=admin_headers)).json()["events"]
    assert ev and ev[0]["details"]["enabled"] == ["3"]
    await client.put("/api/admin/settings", json={"settings": {"ai_themes": "all"}}, headers=admin_headers)


# ── Photographer mode: a switch, not a deletion ─────────────────────────────────────────────────

@pytest.fixture
async def phone(client, admin_token):
    h = {"Authorization": f"Bearer {admin_token}"}
    sid = (await client.post("/api/admin/schools", json={"name": f"Switch {uuid.uuid4().hex[:5]}"}, headers=h)).json()["school"]["id"]
    admin = {**h, "X-School": sid}
    await client.put("/api/admin/settings", json={"settings": {"shoot_mode": True}}, headers=admin)
    await client.post("/api/admin/shoot/token", headers=admin)
    token = (await client.get("/api/admin/shoot", headers=admin)).json()["link"].split("t=")[1]
    return {"admin": admin, "tok": {"X-Shoot-Token": token}, "sid": sid}


async def test_switching_the_mode_off_revokes_the_phone_link(client, phone):
    from services import shoot_service
    assert (await client.get("/api/shoot/info", headers=phone["tok"])).status_code == 200
    await client.put("/api/admin/settings", json={"settings": {"shoot_mode": False}}, headers=phone["admin"])
    assert shoot_service.get_token(phone["sid"]) is None
    assert (await client.get("/api/shoot/info", headers=phone["tok"])).status_code == 401
    ev = (await client.get("/api/admin/audit?action=shoot.revoked", headers=phone["admin"])).json()["events"]
    assert ev and ev[0]["details"] == {"had_link": True}


async def test_switching_it_back_on_needs_a_new_link_the_old_one_stays_dead(client, phone):
    old = phone["tok"]
    await client.put("/api/admin/settings", json={"settings": {"shoot_mode": False}}, headers=phone["admin"])
    await client.put("/api/admin/settings", json={"settings": {"shoot_mode": True}}, headers=phone["admin"])
    assert (await client.get("/api/shoot/info", headers=old)).status_code == 401
    await client.post("/api/admin/shoot/token", headers=phone["admin"])
    fresh = (await client.get("/api/admin/shoot", headers=phone["admin"])).json()["link"].split("t=")[1]
    assert (await client.get("/api/shoot/info", headers={"X-Shoot-Token": fresh})).status_code == 200


async def test_an_unrevoked_link_is_still_refused_while_the_mode_is_off(client, phone):
    """Even a token that survived (restored database, race) opens nothing while the switch is off."""
    from core.db import get_db
    await client.put("/api/admin/settings", json={"settings": {"shoot_mode": False}}, headers=phone["admin"])
    with get_db() as conn:
        conn.execute("INSERT OR REPLACE INTO app_kv (`key`, value) VALUES (?,?)",
                     (f"shoot_token:{phone['sid']}", phone["tok"]["X-Shoot-Token"]))
        conn.commit()
    assert (await client.get("/api/shoot/info", headers=phone["tok"])).status_code == 401


async def test_a_list_ticked_for_another_storyface_app_offers_every_theme(client, admin_headers, themes):
    """The ids ticked when themes came from app 1 name none of today's: hiding the AI offer would be silent."""
    await client.put("/api/admin/settings", json={"settings": {"ai_themes": "5,6"}}, headers=admin_headers)
    try:
        assert await _ids(client, code=DEMO_CODE) == ["3", "78", "800"]
    finally:
        await client.put("/api/admin/settings", json={"settings": {"ai_themes": "all"}}, headers=admin_headers)
