"""Test message limit - guest limit = 3."""
import os
import requests

DEVICE_ID = "limit-test-002"
BASE_URL = os.getenv("BASE_URL", "http://localhost:5000")
API_URL = f"{BASE_URL}/api/agent/chat"


def safe_text(value: str | None) -> str:
    if value is None:
        return ""
    return str(value).encode("ascii", "backslashreplace").decode("ascii")


print("=" * 50)
print("TEST MESSAGE LIMIT (Guest = 3 per day)")
print("=" * 50)
print(f"Device ID: {DEVICE_ID}")
print()

for i in range(5):
    print(f"--- Message #{i + 1} ---")
    response = requests.post(
        API_URL,
        json={"user_query": f"test message {i + 1}"},
        headers={"device_id": DEVICE_ID},
    )
    try:
        data = response.json()
    except ValueError:
        data = {}

    if response.status_code != 200:
        print(f"HTTP {response.status_code}")
        print(f"   Body: {safe_text(response.text)}")
    elif data.get("status") == "success":
        limit_info = data.get("limit_info", {})
        used = limit_info.get("used")
        limit = limit_info.get("limit")
        remaining = limit_info.get("remaining")
        print("OK: allowed")
        print(f"   Used: {used}/{limit}")
        print(f"   Remaining: {remaining}")
    else:
        print("BLOCKED")
        print(f"   Error: {safe_text(data.get('error_code'))}")
        print(f"   Message: {safe_text(data.get('message'))}")
        print(f"   Require login: {data.get('require_login')}")
        limit_info = data.get("limit_info", {})
        if limit_info:
            print(f"   Used: {limit_info.get('used')}/{limit_info.get('limit')}")
        if not data:
            print(f"   Body: {safe_text(response.text)}")
    print()

print("=" * 50)
print("TEST COMPLETE")
