import subprocess
import json
import time

BASE_URL = "http://localhost:5000"

def run_curl(method, endpoint, data=None, token=None):
    cmd = ["curl", "-s", "-X", method, f"{BASE_URL}{endpoint}"]
    cmd += ["-H", "Content-Type: application/json"]
    if token:
        cmd += ["-H", f"Authorization: Bearer {token}"]
    if data:
        cmd += ["-d", json.dumps(data)]
    
    result = subprocess.run(cmd, capture_output=True, text=True)
    try:
        return json.loads(result.stdout)
    except:
        return result.stdout

def test_chatbot():
    print("🚀 Testing Chatbot API...")
    
    # 1. Register to get token
    username = f"chat_user_{int(time.time())}"
    reg_data = {
        "username": username,
        "email": f"{username}@example.com",
        "password": "testpassword123"
    }
    reg_res = run_curl("POST", "/api/v1/auth/register", data=reg_data)
    if "access_token" not in reg_res:
        print("❌ Registration failed:", reg_res)
        return
    
    token = reg_res["access_token"]
    print(f"✅ Registered user: {username}")

    # 2. Test Chatbot (Non-streaming)
    print("📥 Sending chat query...")
    chat_data = {
        "user_query": "Xin chào, bạn là ai?"
    }
    chat_res = run_curl("POST", "/api/agent/chat", data=chat_data, token=token)
    
    if chat_res.get("status") == "success":
        print("✅ Chatbot Response:", chat_res.get("ai_response"))
    else:
        print("❌ Chatbot failed:", chat_res)

    # 3. Test Chatbot (Streaming)
    print("📥 Testing streaming chat...")
    stream_res = run_curl("POST", "/api/agent/chat/stream", data=chat_data, token=token)
    if "data:" in str(stream_res):
        print("✅ Streaming API responded (SSE data detected)")
    else:
        print("❌ Streaming API failed or empty response")

if __name__ == "__main__":
    test_chatbot()
