# app/main.py from fastapi import FastAPI, HTTPException, status from datetime import datetime import threading from models import QuizRequest from config import STUDENT_SECRET from solver import QuizSolver app = FastAPI(title="Quiz Solver API") request_times = {} # Tracks active quiz requests def start_quiz_solving_task(payload: QuizRequest, start_time: datetime): """Function to run the blocking quiz solver in a thread.""" try: solver = QuizSolver(payload, start_time) result = solver.run_quiz_loop() print(f"Quiz finished for {payload.url} with result: {result}") except Exception as e: print(f"Quiz solving task failed: {e}") finally: if payload.url in request_times: del request_times[payload.url] @app.post("/solve-quiz") async def handle_quiz_request( payload: QuizRequest ): """ Receives the quiz request, validates the secret, and starts the solver. """ # 1. Secret Verification if payload.secret != STUDENT_SECRET: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Invalid secret provided." ) start_time = datetime.now() if payload.url in request_times: return {"message": "Quiz already in progress. Ignoring duplicate request."} request_times[payload.url] = start_time # 2. Start the Quiz Solver in a separate thread thread = threading.Thread( target=start_quiz_solving_task, args=(payload, start_time) ) thread.start() # 3. Respond immediately with 200 JSON return { "message": "Quiz solving process started.", "url": payload.url, "email": payload.email } @app.get("/download-log") def download_log(): return FileResponse("app.log", filename="app.log")