import json
from pydantic import ValidationError
from app.schemas.requests import QuizCreateSchema, UserAnswerSchema
from app.schemas.response import QuizCreationResponse
from app.services import QuizService, AnswerService, QuestionGenerationService
from app.helpers import make_response, make_error_response
from app.exception import ValidationException, DataNotFoundException


class QuizController:
    def __init__(
        self,
        quiz_service: QuizService,
        answer_service: AnswerService,
        question_generate_service: QuestionGenerationService,
    ):
        self.quiz_service = quiz_service
        self.answer_service = answer_service
        self.question_generate_service = question_generate_service

    def get_quiz(self, quiz_id):
        try:
            result = self.quiz_service.get_quiz(quiz_id)
            if not result:
                return make_response(message="Quiz not found", status_code=404)
            return make_response(message="Quiz Found", data=result.model_dump())
        except DataNotFoundException as e:
            return make_response(message=e.message, status_code=e.status_code)
        except Exception as e:
            return make_error_response(e)

    def create_quiz(self, quiz_data):
        try:
            quiz_obj = QuizCreateSchema(**quiz_data)
            quiz_id = self.quiz_service.create_quiz(quiz_obj)
            return make_response(
                message="Quiz created",
                data=QuizCreationResponse(quiz_id=quiz_id),
                status_code=201,
            )
        except (ValidationError, ValidationException) as e:
            return make_response(message="", status_code=400)
        except Exception as e:
            return make_error_response(e)

    def quiz_recomendation(self):
        try:
            result = self.quiz_service.get_quiz_recommendation()
            if not result:
                return make_response(message="Quiz not found", status_code=404)
            return make_response(message="Quiz Found", data=result.model_dump())
        except Exception as e:
            return make_error_response(e)

    def submit_answer(self, answer_data):
        try:
            answer_obj = UserAnswerSchema(**answer_data)
            answer_id = self.answer_service.create_answer(answer_obj)
            return make_response(
                message="Answer submitted",
                data={"answer_id": answer_id},
                status_code=201,
            )
        except ValidationError as e:
            return make_response(
                message="validation error", data=json.loads(e.json()), status_code=400
            )
        except ValidationException as e:
            return make_response(
                message=f"validation issue {e.message}", status_code=400
            )
        except Exception as e:
            return make_error_response(e)

    def get_answer(self, quiz_id, user_id, session_id):
        try:
            # self.answer_service.
            print("yps")
        except Exception as e:
            return make_error_response(e)

    def get_user_quiz(self, user_id, page=1, page_size=10):
        try:
            result = self.quiz_service.get_user_quiz(
                user_id=user_id, page=page, page_size=page_size
            )
            return make_response(
                message="User quizzes retrieved successfully",
                data=result.quizzes,
                page=page,
                page_size=page_size,
                total_all_data=result.total,
            )
        except Exception as e:
            return make_error_response(e)

    def get_quiz_recommendation(self, page, limit):
        try:
            page = int(page) if page is not None else 1
            limit = int(limit) if limit is not None else 3
            result = self.quiz_service.get_quiz_recommendation(page=page, limit=limit)
            return make_response(
                message="success retrieve recommendation quiz", data=result
            )
        except DataNotFoundException as e:
            return make_response(message=e.message, status_code=e.status_code)
        except ValueError as e:
            return make_response(message=str(e), data=None, status_code=400)
        except ValidationError as e:
            return make_response(
                message="validation error", data=json.loads(e.json()), status_code=400
            )
        except Exception as e:
            return make_error_response(e)

    def search_quiz(self, keyword: str, subject_id: str, page: int, limit: int):
        try:
            quiz, total = self.quiz_service.search_quiz(
                keyword, subject_id, page, limit
            )
            return make_response(
                message="success",
                data=quiz,
                page=page,
                page_size=limit,
                total_all_data=total,
            )
        except Exception as e:
            return make_error_response(e)

    def create_quiz_auto(
        self,
        reqBody,
    ):
        try:
            result = self.question_generate_service.createQuizAutomate(
                reqBody["sentence"]
            )
            return make_response(message="succes labeling", data=result)
        except Exception as e:
            return make_error_response(e)
