from __future__ import annotations

from fastapi.testclient import TestClient

from eightmem.services.telegram_service import process_telegram_message
from eightmem.ui.app import create_app


def test_files_view_can_show_user_scoped_memory(fake_home):
    process_telegram_message(user_id="tg-user-99", text="Remember: avoid emojis")
    client = TestClient(create_app())

    response = client.get("/files?user_id=tg-user-99")

    assert response.status_code == 200
    assert "Avoid emojis." in response.text


def test_export_view_can_show_user_scoped_memory(fake_home):
    process_telegram_message(user_id="tg-user-98", text="Remember: keep answers concise")
    client = TestClient(create_app())

    response = client.get("/export?user_id=tg-user-98")

    assert response.status_code == 200
    assert "Keep answers concise." in response.text
    assert "\n# PREFERENCES\n" not in response.text


def test_user_scoped_views_canonicalize_stale_preference_entries(fake_home):
    process_telegram_message(user_id="tg-user-96", text="Remember: keep answers concise")
    client = TestClient(create_app())

    response = client.get("/files/PREFERENCES.md?user_id=tg-user-96")

    assert response.status_code == 200
    assert "Keep answers concise." in response.text
    assert "Prefers keep answers concise." not in response.text


def test_user_scoped_file_save_preserves_query_param(fake_home):
    process_telegram_message(user_id="tg-user-97", text="Remember: avoid emojis")
    client = TestClient(create_app())

    new_content = "# PREFERENCES\n\nStable response and formatting preferences.\n\n## Entries\n\n- Keep answers concise.\n"
    response = client.post(
        "/files/PREFERENCES.md?user_id=tg-user-97",
        data={"content": new_content},
        follow_redirects=False,
    )

    assert response.status_code == 303
    assert response.headers["location"] == "/files/PREFERENCES.md?user_id=tg-user-97"
