"""Platform settings (app/core/platform_settings.py): the Super Admin's
overrides of .env. These touch only low-impact settings and always clear
them — a dev server on the same database picks overrides up too."""

import uuid

import pytest
from sqlalchemy import text

from app.core import platform_settings
from app.core.auth import create_platform_admin_token, hash_password
from app.core.config import settings
from app.models.platform_admin import PlatformAdmin
from tests.conftest import AsyncSessionLocal

KEYS = ("CLOUD_PROVIDER_LABEL", "CLOUD_API_KEY", "JWT_EXPIRY_MINUTES", "OLLAMA_BASE_URL")


@pytest.fixture
async def super_admin():
    async with AsyncSessionLocal() as db:
        async with db.begin():
            admin = PlatformAdmin(
                name="Pytest Super Admin", email=f"pytest-super-{uuid.uuid4().hex[:8]}@example.com",
                password_hash=hash_password("pytest-password-123"), status="active",
            )
            db.add(admin)
            await db.flush()
            admin_id = admin.id
    yield {"Authorization": f"Bearer {create_platform_admin_token(admin_id=admin_id)}"}
    async with AsyncSessionLocal() as db:
        async with db.begin():
            for key in KEYS:
                await platform_settings.clear(db, key)
            await db.execute(text("DELETE FROM platform_admins WHERE id = :id"), {"id": admin_id})


def _by_key(listing) -> dict:
    return {s["key"]: s for s in listing}


async def test_settings_are_listed_without_their_secrets(client, super_admin):
    listing = _by_key((await client.get("/admin/platform-settings", headers=super_admin)).json())
    assert listing["JWT_SECRET"]["value"] is None and listing["JWT_SECRET"]["editable"] is False
    assert listing["WORKSPACE_ENCRYPTION_KEY"]["value"] is None
    if ":" in (settings.database_url.split("@")[0].split("//")[-1]):
        assert "••••" in listing["DATABASE_URL"]["value"]
    assert listing["CORS_ORIGINS"]["restart"] is True
    assert listing["CLOUD_PROVIDER_LABEL"]["source"] in ("env", "default")
    # .env-only settings can't be changed here.
    resp = await client.put("/admin/platform-settings/JWT_SECRET", headers=super_admin, json={"value": "x"})
    assert resp.status_code == 422 and "only be set in .env" in resp.json()["detail"]


async def test_an_override_applies_at_once_and_clears_back_to_env(client, super_admin):
    before = settings.cloud_provider_label
    resp = await client.put("/admin/platform-settings/CLOUD_PROVIDER_LABEL", headers=super_admin, json={"value": "  Pytest Cloud  "})
    assert resp.status_code == 200, resp.text
    row = _by_key(resp.json())["CLOUD_PROVIDER_LABEL"]
    assert row["value"] == "Pytest Cloud" and row["source"] == "override" and row["updated_by"] == "Pytest Super Admin"
    assert settings.cloud_provider_label == "Pytest Cloud"

    resp = await client.delete("/admin/platform-settings/CLOUD_PROVIDER_LABEL", headers=super_admin)
    assert _by_key(resp.json())["CLOUD_PROVIDER_LABEL"]["source"] in ("env", "default")
    assert settings.cloud_provider_label == before


async def test_values_are_checked_against_their_type(client, super_admin):
    put = lambda key, value: client.put(f"/admin/platform-settings/{key}", headers=super_admin, json={"value": value})  # noqa: E731
    assert (await put("JWT_EXPIRY_MINUTES", "soon")).status_code == 422
    assert (await put("JWT_EXPIRY_MINUTES", "1")).status_code == 422
    assert (await put("OLLAMA_BASE_URL", "ftp://x")).status_code == 422
    assert (await put("AI_PROVIDER", "skynet")).status_code == 422
    assert (await put("PUBLIC_TENANT_LIST", "maybe")).status_code == 422
    ok = await put("JWT_EXPIRY_MINUTES", "90")
    assert ok.status_code == 200 and settings.jwt_expiry_minutes == 90
    ok = await put("OLLAMA_BASE_URL", "http://ollama.internal:11434/")
    assert ok.status_code == 200 and settings.ollama_base_url == "http://ollama.internal:11434"


async def test_a_secret_is_stored_encrypted_and_never_sent_back(client, super_admin):
    resp = await client.put("/admin/platform-settings/CLOUD_API_KEY", headers=super_admin, json={"value": "sk-pytest-123"})
    row = _by_key(resp.json())["CLOUD_API_KEY"]
    assert row["value"] is None and row["has_value"] is True and "sk-pytest-123" not in resp.text
    assert settings.cloud_api_key == "sk-pytest-123"
    async with AsyncSessionLocal() as db:
        stored = (await db.execute(text("SELECT value, secret FROM platform_settings WHERE key = 'CLOUD_API_KEY'"))).one()
    assert stored.secret and "sk-pytest-123" not in stored.value


async def test_another_processes_change_is_picked_up(super_admin):
    """What refresh_loop does every half minute in each process."""
    before = settings.cloud_provider_label
    async with AsyncSessionLocal() as db:
        async with db.begin():
            await db.execute(text("INSERT INTO platform_settings (key, value) VALUES ('CLOUD_PROVIDER_LABEL', 'From elsewhere')"))
    async with AsyncSessionLocal() as db:
        await platform_settings.load(db)
    assert settings.cloud_provider_label == "From elsewhere"
    async with AsyncSessionLocal() as db:
        async with db.begin():
            await db.execute(text("DELETE FROM platform_settings WHERE key = 'CLOUD_PROVIDER_LABEL'"))
    async with AsyncSessionLocal() as db:
        await platform_settings.load(db)
    assert settings.cloud_provider_label == before
