from workers import WorkerEntrypoint, Response
# from urllib.parse import urlparse, parse_qs
import json
# import random
# import string

# def get_random_id():
#     return ''.join(random.choice(string.ascii_lowercase) for _ in range(10))

class Default(WorkerEntrypoint):
    async def fetch(self, request):
        # parsed_url = urlparse(request.url)
        # path = parsed_url.path
        # query_params = parse_qs(parsed_url.query)

        # if request.method == "GET" and path == "/api/new-participant":
        #     return await self.register_new_participant()

        # elif request.method == "GET" and path == "/api/question":
        #     participant_id = query_params.get("participant", [""])[0]
        #     if participant_id == "":
        #         return Response(json.dumps({"error": "Missing participant ID"}), headers={"Content-Type": "application/json"}, status=400)
        #     return await self.get_question(participant_id)

        # elif request.method == "POST" and path == "/api/submit":
        #      return await self.submit_response(request)
        
        # elif request.method == "GET" and path == "/api/participant":
        #     participant_id = query_params.get("participant", [""])[0]
        #     if participant_id == "":
        #         return Response(json.dumps({"error": "Missing participant ID"}), headers={"Content-Type": "application/json"}, status=400)
        #     return await self.get_participant(participant_id)
                
        # STUDY IS CLOSED
        return Response(json.dumps({"error": "Not found"}), headers={"Content-Type": "application/json"}, status=404)

    # async def register_new_participant(self):
    #     new_id = get_random_id()

    #     try:
    #         result = await self.env.study_database.prepare("INSERT INTO participants (participant_id) VALUES (?)").bind(new_id).run()
    #     except:
    #         return Response(json.dumps({"error": "Error registering new participant"}), headers={"Content-Type": "application/json"}, status=500)

    #     if not result.success:
    #         return Response(json.dumps({"error": "Error registering new participant"}), headers={"Content-Type": "application/json"}, status=500)
        
    #     return Response(json.dumps({"participant_id": new_id}), headers={"Content-Type": "application/json"})

    # async def get_sub_concept_question(self, participant_id):
    #     question = await self.env.study_database.prepare("SELECT sub_concept_id, sub_concept, parent_concept FROM sub_concepts WHERE sub_concept_id NOT IN (SELECT sub_concept_id FROM sub_concept_responses WHERE participant_id = ?) ORDER BY RANDOM() LIMIT 1").bind(participant_id).first()
    #     if question:
    #         question = question.to_py()
    #         question["type"] = "sub_concept"
    #     return question

    # async def get_image_question(self, participant_id):
    #     question = await self.env.study_database.prepare("UPDATE images SET assigned_to_participant = ?, assigned_at = strftime('%s', 'now') WHERE image_id = (SELECT image_id FROM images WHERE is_answered = 0 AND (assigned_to_participant IS NULL OR assigned_at < (strftime('%s', 'now') - 3600)) ORDER BY RANDOM() LIMIT 1) RETURNING image_id, concept, image_file").bind(participant_id).first()
    #     if question:
    #         question = question.to_py()
    #         question["type"] = "image"
    #     return question

    # async def get_question(self, participant_id):
    #     matching_participant = await self.env.study_database.prepare("SELECT * FROM participants WHERE participant_id = ?").bind(participant_id).first()

    #     if not matching_participant:
    #         return Response(json.dumps({"error": "Participant ID not found"}), headers={"Content-Type": "application/json"}, status=404)
    #     number_answered = matching_participant.sub_concepts_answered + matching_participant.images_answered
    #     if number_answered >= 100:
    #         return Response(json.dumps({"question_available": False}), headers={"Content-Type": "application/json"}, status=200)

    #     question_options = [
    #         self.get_sub_concept_question,
    #         self.get_image_question
    #     ]
    #     random.shuffle(question_options)
    #     question = await question_options[0](participant_id)
    #     if not question:
    #         question = await question_options[1](participant_id)            

    #     if not question:
    #         return Response(json.dumps({"question_available": False}), headers={"Content-Type": "application/json"}, status=200)
        
    #     question["number_answered"] = number_answered
    #     question["question_available"] = True

    #     return Response(json.dumps(question), headers={"Content-Type": "application/json"})

    # async def submit_response(self, request):
    #     try:
    #         body = await request.json()
    #     except:
    #         return Response(json.dumps({"error": "Invalid JSON"}), headers={"Content-Type": "application/json"}, status=400)
    #     if (not body
    #         or "participant_id" not in body
    #         or "question_type" not in body
    #         or body["question_type"] not in ["sub_concept", "image"]
    #         or "question_id" not in body
    #         or "response" not in body
    #         or ((body["question_type"] == "sub_concept") and (body["response"] not in [0, 1, 2, 100]))
    #         or ((body["question_type"] == "image") and (body["response"] not in [0, 1, 100]))):
    #         return Response(json.dumps({"error": "Invalid request body"}), headers={"Content-Type": "application/json"}, status=400)

    #     matching_participant = await self.env.study_database.prepare("SELECT * FROM participants WHERE participant_id = ?").bind(body["participant_id"]).first()

    #     if not matching_participant:
    #         return Response(json.dumps({"error": "Participant ID not found"}), headers={"Content-Type": "application/json"}, status=404)

    #     if body["question_type"] == "sub_concept":
    #         seq = matching_participant.sub_concepts_answered + 1
    #         result = await self.env.study_database.prepare("INSERT INTO sub_concept_responses (sub_concept_id, participant_id, response, seq) VALUES (?, ?, ?, ?)").bind(body["question_id"], body["participant_id"], body["response"], seq).run()
    #     elif body["question_type"] == "image":
    #         seq = matching_participant.images_answered + 1
    #         result = await self.env.study_database.prepare("UPDATE images SET participant_response = ?, is_answered = 1, seq = ? WHERE image_id = ? AND assigned_to_participant = ? AND is_answered = 0").bind(body["response"], seq, body["question_id"], body["participant_id"]).run()
    #     if not result.success:
    #         return Response(json.dumps({"error": "Error submitting response"}), headers={"Content-Type": "application/json"}, status=400)
        
    #     if body["question_type"] == "sub_concept":
    #         await self.env.study_database.prepare("UPDATE participants SET sub_concepts_answered = sub_concepts_answered + 1 WHERE participant_id = ?").bind(body["participant_id"]).run()
    #     elif body["question_type"] == "image":
    #         await self.env.study_database.prepare("UPDATE participants SET images_answered = images_answered + 1 WHERE participant_id = ?").bind(body["participant_id"]).run()

    #     return await self.get_question(body["participant_id"])

    # async def get_participant(self, participant_id):
    #     participant = await self.env.study_database.prepare("SELECT * FROM participants WHERE participant_id = ?").bind(participant_id).first()

    #     if not participant:
    #         return Response(json.dumps({"error": "Participant ID not found"}), headers={"Content-Type": "application/json"}, status=404)

    #     complete = participant.sub_concepts_answered + participant.images_answered >= 100
    #     return Response(json.dumps({"complete": complete}), headers={"Content-Type": "application/json"})
