# retoor <retoor@molodetz.nl>

from playwright.sync_api import expect
from tests.conftest import BASE_URL
from devplacepy.database import get_table, refresh_snapshot
from devplacepy.utils import clear_user_cache


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


def _reset(uid):
    get_table("users").update(
        {"uid": uid, "ai_correction_enabled": 0, "ai_correction_sync": 0}, ["uid"]
    )
    clear_user_cache(uid)


def _profile(page, username):
    page.goto(f"{BASE_URL}/profile/{username}", wait_until="domcontentloaded")


def test_owner_sees_ai_correction_block(bob):
    page, user = bob
    _reset(_user(user["username"])["uid"])
    _profile(page, user["username"])
    expect(page.locator("[data-ai-correction]")).to_be_visible()
    expect(page.locator("[data-ai-correction-save]")).to_be_visible()


def test_owner_enables_and_saves(bob):
    page, user = bob
    uid = _user(user["username"])["uid"]
    _reset(uid)
    _profile(page, user["username"])

    toggle = page.locator("[data-ai-correction-toggle]")
    if not toggle.is_checked():
        toggle.check()
    page.locator("[data-ai-correction-prompt]").fill("Fix only casing and punctuation")
    page.locator("[data-ai-correction-save]").click()

    expect(page.locator("[data-ai-correction-status]")).to_have_text("Saved", timeout=10000)

    refresh_snapshot()
    row = get_table("users").find_one(uid=uid)
    assert row["ai_correction_enabled"] == 1
    assert row["ai_correction_prompt"] == "Fix only casing and punctuation"


def test_non_owner_does_not_see_block(bob, seeded_db):
    page, user = bob
    _profile(page, seeded_db["alice"]["username"])
    expect(page.locator("[data-ai-correction]")).to_have_count(0)
