# retoor <retoor@molodetz.nl>

import time
import pytest
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table, refresh_snapshot, set_setting

JSON = {"Accept": "application/json"}
_counter_aic = [0]


@pytest.fixture(scope="module", autouse=True)
def _settings(app_server):
    set_setting("rate_limit_per_minute", "1000000")
    set_setting("registration_open", "1")
    yield


def _member():
    _counter_aic[0] += 1
    name = f"aic{int(time.time() * 1000)}{_counter_aic[0]}"
    requests.post(
        f"{BASE_URL}/auth/signup",
        data={
            "username": name,
            "email": f"{name}@t.dev",
            "password": "secret123",
            "confirm_password": "secret123",
            "birth_date": "1990-01-01",
            "accept_terms": "1",
        },
        allow_redirects=True,
    )
    refresh_snapshot()
    user = get_table("users").find_one(username=name)
    return name, user["uid"], user["api_key"]


def _admin_key(seeded_db):
    refresh_snapshot()
    return get_table("users").find_one(username="alice_test")["api_key"]


def test_owner_enables_correction(app_server):
    name, uid, key = _member()
    r = requests.post(
        f"{BASE_URL}/profile/{name}/ai-correction",
        headers={"X-API-KEY": key, **JSON},
        data={"enabled": "true", "sync": "true", "prompt": "fix casing only"},
    )
    assert r.status_code == 200, r.text[:200]
    body = r.json()["data"]
    assert body["enabled"] is True and body["sync"] is True
    refresh_snapshot()
    row = get_table("users").find_one(uid=uid)
    assert row["ai_correction_enabled"] == 1
    assert row["ai_correction_sync"] == 1
    assert row["ai_correction_prompt"] == "fix casing only"


def test_owner_disables_correction(app_server):
    name, uid, key = _member()
    requests.post(
        f"{BASE_URL}/profile/{name}/ai-correction",
        headers={"X-API-KEY": key, **JSON},
        data={"enabled": "true"},
    )
    r = requests.post(
        f"{BASE_URL}/profile/{name}/ai-correction",
        headers={"X-API-KEY": key, **JSON},
        data={"enabled": "false"},
    )
    assert r.status_code == 200
    refresh_snapshot()
    assert get_table("users").find_one(uid=uid)["ai_correction_enabled"] == 0


def test_empty_prompt_falls_back_to_default(app_server):
    from devplacepy.config import DEFAULT_CORRECTION_PROMPT

    name, uid, key = _member()
    r = requests.post(
        f"{BASE_URL}/profile/{name}/ai-correction",
        headers={"X-API-KEY": key, **JSON},
        data={"enabled": "true", "prompt": "   "},
    )
    assert r.status_code == 200
    assert r.json()["data"]["prompt"] == DEFAULT_CORRECTION_PROMPT


def test_admin_sets_for_other_user(seeded_db):
    name, uid, key = _member()
    r = requests.post(
        f"{BASE_URL}/profile/{name}/ai-correction",
        headers={"X-API-KEY": _admin_key(seeded_db), **JSON},
        data={"enabled": "true"},
    )
    assert r.status_code == 200
    refresh_snapshot()
    assert get_table("users").find_one(uid=uid)["ai_correction_enabled"] == 1


def test_non_owner_forbidden(app_server):
    name, uid, key = _member()
    _, _, other_key = _member()
    r = requests.post(
        f"{BASE_URL}/profile/{name}/ai-correction",
        headers={"X-API-KEY": other_key, **JSON},
        data={"enabled": "true"},
    )
    assert r.status_code == 403


def test_guest_rejected(app_server):
    name, uid, key = _member()
    r = requests.post(
        f"{BASE_URL}/profile/{name}/ai-correction",
        headers=JSON,
        data={"enabled": "true"},
        allow_redirects=False,
    )
    assert r.status_code in (401, 303)
