"""
TEST SCRIPT FOR MESSAGE LIMIT V2
Logic:
- Guest limit: 10
- Total limit (guest + user): 100
"""
import os
import requests

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


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


def send_msg(i: int, is_login: bool = False) -> None:
    headers = {"device_id": DEVICE_ID}
    if is_login:
        headers["X-Dev-User-Id"] = "user_123"
        user_status = "USER "
    else:
        user_status = "GUEST"

    print(f"[{user_status}] Msg #{i} sending...", end=" ")
    try:
        resp = requests.post(
            API_URL,
            json={"user_query": f"test msg {i}"},
            headers=headers,
        )
        try:
            data = resp.json()
        except ValueError:
            data = {}

        if resp.status_code != 200:
            print(f"HTTP {resp.status_code}: {safe_text(resp.text)}")
        elif data.get("status") == "success":
            limit = data.get("limit_info", {})
            print(
                f"OK: used {limit.get('used')}/{limit.get('limit')} "
                f"| remaining {limit.get('remaining')}"
            )
        else:
            print(f"BLOCKED: {safe_text(data.get('message'))}")
            if "limit_info" in data:
                print(f"   Info: {safe_text(data.get('limit_info'))}")
            if not data:
                print(f"   Body: {safe_text(resp.text)}")
    except Exception as exc:
        print(f"ERROR: {exc}")


print(f"=== START TEST V2 (Device: {DEVICE_ID}) ===")
print("=" * 60)

print("\n--- PHASE 1: GUEST (3 msgs) ---")
for i in range(1, 4):
    send_msg(i, is_login=False)

print("\n--- PHASE 2: LOGIN (USER) ---")
send_msg(4, is_login=True)

print("\n--- CHECK INFO ---")
try:
    resp = requests.get(
        f"{BASE_URL}/api/message-limit",
        headers={"device_id": DEVICE_ID},
    )
    print(f"Guest View ({resp.status_code}): {safe_text(resp.text)}")

    resp = requests.get(
        f"{BASE_URL}/api/message-limit",
        headers={"device_id": DEVICE_ID, "X-Dev-User-Id": "user_123"},
    )
    print(f"User View ({resp.status_code}): {safe_text(resp.text)}")
except Exception:
    pass
