import subprocess
import json
import time
import sys

BASE_URL = "http://localhost:5000"

def run_curl(method, endpoint, data=None, token=None, files=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_all():
    print("🚀 STARTING COMPREHENSIVE API TEST...")
    
    # --- 1. AUTH ---
    timestamp = int(time.time())
    username = f"user_{timestamp}"
    print(f"Checking Auth (Register {username})...")
    reg_data = {"username": username, "email": f"{username}@test.com", "password": "password123"}
    auth_res = run_curl("POST", "/api/v1/auth/register", data=reg_data)
    if "access_token" not in auth_res:
        print("❌ AUTH FAILED:", auth_res)
        return
    token = auth_res["access_token"]
    print("✅ Auth OK")

    # --- 2. MEMOS ---
    print("Checking Memos...")
    memo_data = {"content": f"Test memo {timestamp}", "visibility": "PUBLIC"}
    memo_res = run_curl("POST", "/api/v1/memos", data=memo_data, token=token)
    if "id" not in memo_res:
        print("❌ MEMO CREATE FAILED:", memo_res)
    else:
        memo_id = memo_res["uid"]
        print(f"✅ Memo Created (uid: {memo_id})")
        
        # Test Comment
        comment_data = {"content": "Test comment"}
        comment_res = run_curl("POST", f"/api/v1/memos/{memo_id}/comments", data=comment_data, token=token)
        print("✅ Comment OK" if "id" in comment_res else f"❌ Comment Failed: {comment_res}")

        # Test Reaction
        react_data = {"reactionType": "👍"}
        react_res = run_curl("POST", f"/api/v1/memos/{memo_id}/reactions", data=react_data, token=token)
        print("✅ Reaction OK" if "reactionType" in react_res else f"❌ Reaction Failed: {react_res}")

    # --- 3. SEARCH ---
    print("Checking Search...")
    search_res = run_curl("GET", f"/api/v1/memos/search?q=Test", token=token)
    if isinstance(search_res, dict) and "hits" in search_res:
        print(f"✅ Search OK ({len(search_res['hits'])} hits)")
    else:
        print("❌ Search Failed:", search_res)

    # --- 4. TEAMS ---
    print("Checking Teams...")
    team_data = {"name": f"Team {timestamp}", "description": "Test team"}
    team_res = run_curl("POST", "/api/v1/teams", data=team_data, token=token)
    if "id" in team_res:
        team_id = team_res["id"]
        print(f"✅ Team Created (id: {team_id})")
        
        # List teams
        list_teams = run_curl("GET", "/api/v1/teams", token=token)
        print("✅ Team List OK" if len(list_teams) > 0 else "❌ Team List Failed")
    else:
        print("❌ Team Create Failed:", team_res)

    # --- 5. CHATBOT ---
    print("Checking Chatbot (Lazy-loading LLM, please wait)...")
    chat_data = {"user_query": "Hello"}
    chat_res = run_curl("POST", "/api/agent/chat", data=chat_data, token=token)
    if isinstance(chat_res, dict) and chat_res.get("status") == "success":
        print("✅ Chatbot OK:", chat_res.get("ai_response")[:50], "...")
    else:
        print("❌ Chatbot Failed:", chat_res)

    print("\n🏁 TEST COMPLETE.")

if __name__ == "__main__":
    test_all()
