import sys
import httpx

def main():
    with httpx.Client(base_url="http://localhost:8000") as client:
        # First, register and login
        username = "testuser_history"
        password = "password123"
        r = client.post("/users", json={"username": username, "password": password})
        if r.status_code not in (200, 201):
            if "already registered" not in r.text:
                print(f"Failed to create user: {r.text}")
                sys.exit(1)
        
        # Login
        r = client.post("/token", data={"username": username, "password": password})
        if r.status_code != 200:
            print(f"Failed to login: {r.text}")
            sys.exit(1)
            
        token = r.json()["access_token"]
        headers = {"Authorization": f"Bearer {token}"}
        
        # Post History
        quiz_id = "react-basic"
        payload = {
            "quiz_id": quiz_id,
            "passed_questions": [1, 2, 3],
            "failed_questions": [4, 5]
        }
        
        print("Testing POST /history...")
        r = client.post(f"/quizzes/{quiz_id}/history", json=payload, headers=headers)
        if r.status_code != 200:
            print(f"Failed POST: {r.status_code} {r.text}")
            sys.exit(1)
            
        print(f"POST Result: {r.json()}")
        
        # Get History
        print("Testing GET /history...")
        r = client.get(f"/quizzes/{quiz_id}/history", headers=headers)
        if r.status_code != 200:
            print(f"Failed GET: {r.status_code} {r.text}")
            sys.exit(1)
            
        print(f"GET Result: {r.json()}")

        # Start Quiz Excluded
        print("Testing GET /start?exclude_practiced=true...")
        r = client.get(f"/quizzes/{quiz_id}/start?mode=practice&limit=20&exclude_practiced=true", headers=headers)
        if r.status_code != 200:
             print(f"Failed START: {r.status_code} {r.text}")
             sys.exit(1)
        
        questions = r.json()["questions"]
        q_ids = [q["id"] for q in questions]
        print(f"Returned Question IDs: {q_ids}")
        for passed_id in [1, 2, 3]:
             if passed_id in q_ids:
                 print(f"FAILED: Excluded ID {passed_id} was returned in the quiz!")
                 sys.exit(1)
        
        print("SUCCESS! History logic works perfectly.")

if __name__ == "__main__":
    main()
