import os
import asyncio
import sys
import uuid
from pathlib import Path

from fastapi.testclient import TestClient

# Ensure local/dev friendly toggles before importing app
os.environ["DISABLE_AUTH"] = "true"
os.environ["USE_SQLITE_HISTORY"] = "true"
os.environ["REDIS_CACHE_TURN_ON"] = "false"

ROOT_DIR = Path(__file__).resolve().parent
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

from server import app  # noqa: E402
from common.conversation_manager import get_conversation_manager  # noqa: E402


def test_sqlite_conversation_manager_roundtrip():
    async def _run():
        mgr = await get_conversation_manager()
        identity_key = f"tester-{uuid.uuid4()}"

        await mgr.clear_history(identity_key)
        await mgr.save_conversation_turn(identity_key, "hello", '{"ai_response": "world"}')
        history = await mgr.get_chat_history(identity_key)

        # Two entries: human then AI (ordered DESC by id)
        assert len(history) == 2
        assert any(not entry["is_human"] for entry in history)
        assert any(entry.get("message") == "world" for entry in history)

    asyncio.run(_run())


def test_history_endpoint_returns_data():
    client = TestClient(app)

    # Using random device to avoid collisions
    device_id = f"dev-{uuid.uuid4()}"
    resp = client.get("/api/history/any", headers={"device_id": device_id})
    assert resp.status_code == 200

    payload = resp.json()
    assert "data" in payload
    assert isinstance(payload["data"], list)
