from __future__ import annotations import asyncio import sqlite3 import stat from datetime import date from pathlib import Path import httpx from fastapi.testclient import TestClient from app.config import Settings from app.main import create_app from app.research import ResearchIntent, ResearchStore, ResearchTopic, classify_research def success_transport() -> httpx.MockTransport: async def handler(request: httpx.Request) -> httpx.Response: body = httpx.Response(200, content=request.read()).json() return httpx.Response( 200, json={ "model": body["model"], "choices": [{"message": {"content": "Antwort mit Link."}}], }, ) return httpx.MockTransport(handler) def rows(path: Path) -> list[tuple[str, str, str, int]]: with sqlite3.connect(path) as connection: return connection.execute( "SELECT day_utc, dimension, category, count " "FROM research_daily_counts ORDER BY dimension, category" ).fetchall() def test_classifier_returns_only_allowlisted_categories() -> None: assert classify_research("Wo kann ich Musik anhören?") == ( ResearchTopic.AUDIO_RADIO, ResearchIntent.CONSUME, ) assert classify_research("Mein Name ist Ada und meine Nummer ist 123") == ( ResearchTopic.OTHER, ResearchIntent.OTHER, ) def test_store_keeps_only_daily_aggregate_counts(tmp_path: Path) -> None: database = tmp_path / "private" / "research.sqlite3" store = ResearchStore(str(database), utc_day=lambda: date(2026, 9, 9)) asyncio.run(store.increment(ResearchTopic.VIDEO, ResearchIntent.NAVIGATION)) asyncio.run(store.increment(ResearchTopic.VIDEO, ResearchIntent.NAVIGATION)) assert rows(database) == [ ("2026-09-09", "intent", "navigation", 2), ("2026-09-09", "topic", "video", 2), ] assert stat.S_IMODE(database.parent.stat().st_mode) == 0o700 assert stat.S_IMODE(database.stat().st_mode) == 0o600 def test_successful_chat_counts_categories_without_raw_question(tmp_path: Path) -> None: database = tmp_path / "private" / "research.sqlite3" question = "Wo kann ich das KTN Video ansehen? SENTINEL_RAW_QUESTION" app = create_app( Settings( openrouter_api_key="test-key-not-a-secret", environment="test", market_research_enabled=True, market_research_database_path=str(database), ), transport=success_transport(), ) with TestClient(app) as client: response = client.post("/api/fuugi", json={"message": question}) assert response.status_code == 200 stored = rows(database) assert len(stored) == 2 assert {row[1] for row in stored} == {"topic", "intent"} assert question.encode() not in database.read_bytes() def test_failed_chat_does_not_increment_research(tmp_path: Path) -> None: database = tmp_path / "private" / "research.sqlite3" app = create_app( Settings( openrouter_api_key="", environment="test", market_research_enabled=True, market_research_database_path=str(database), ), transport=success_transport(), ) with TestClient(app) as client: response = client.post("/api/fuugi", json={"message": "Artists"}) assert response.status_code == 503 assert rows(database) == []