"""
TEST SCRIPT FOR MESSAGE LIMIT V2
Logic:
- Guest Limit: 10
- Total Limit (Guest + User): 100
- Support Memory & Redis
"""
import requests
import time

API_URL = "http://localhost:5000/api/agent/chat"
DEVICE_ID = "v2_test_device_003"
USER_TOKEN = "Bearer test_token_123" # Mock token (nếu dev mode support)

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

def send_msg(i, is_login=False):
    headers = {"device_id": DEVICE_ID}
    if is_login:
        headers["X-Dev-User-Id"] = "user_123" # Bypass auth middleware
        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
        )
        data = resp.json()
        
        if data.get("status") == "success":
            limit = data['limit_info']
            print(f"✅ OK! Used: {limit['used']}/{limit['limit']} | Remaining: {limit['remaining']}")
        else:
            print(f"❌ BLOCKED! {data.get('message')}")
            if 'limit_info' in data:
                print(f"   Info: {data['limit_info']}")
                
    except Exception as e:
        print(f"ERROR: {e}")

# 1. Gửi 3 tin Guest
print("\n--- PHASE 1: GUEST (3 msgs) ---")
for i in range(1, 4):
    send_msg(i, is_login=False)

# 2. Login và gửi tiếp
print("\n--- PHASE 2: LOGIN (USER) ---")
send_msg(4, is_login=True)

# 3. Check info
print("\n--- CHECK INFO ---")
try:
    resp = requests.get(
        "http://localhost:5000/api/message-limit",
        headers={"device_id": DEVICE_ID} # Check as guest
    )
    print("Guest View:", resp.json())
    
    resp = requests.get(
        "http://localhost:5000/api/message-limit",
        headers={"device_id": DEVICE_ID, "X-Dev-User-Id": "user_123"} # Check as user
    )
    print("User View:", resp.json())
except:
    pass
