from typing import List, Optional

from pydantic import BaseModel, Field


class KOQuestion(BaseModel):
    title: str = Field(..., description="The title of the knockout criterium.")
    question: str = Field(..., description="The corresponding question asked to the candidate.")
    answer_positive: Optional[str] = Field(None, description="The answer to the question, resulting in a positive outcome.")
    additional_answer_positive: Optional[str] = Field(None, description="2nd answer to the question, resulting in a positive outcome.")
    answer_negative: Optional[str] = Field(None, description="The answer to the question, resulting in a negative outcome.")
    additional_answer_negative: Optional[str] = Field(None, description="2nd answer to the question, resulting in a negative outcome.")

    @classmethod
    def from_json(cls, json_str: str) -> 'KOQuestion':
        """Deserialize from JSON string"""
        return cls.model_validate_json(json_str)

    def to_json(self, **kwargs) -> str:
        """Serialize to JSON string"""
        return self.model_dump_json(**kwargs)


class KOQuestions(BaseModel):
    ko_questions: List[KOQuestion] = Field(
        default_factory=list,
        description="KO Questions and answers."
    )

    @classmethod
    def from_json(cls, json_str: str) -> 'KOQuestions':
        """Deserialize from JSON string"""
        return cls.model_validate_json(json_str)

    def to_json(self, **kwargs) -> str:
        """Serialize to JSON string"""
        return self.model_dump_json(**kwargs)

    @classmethod
    def from_question_list(cls, questions: List[KOQuestion]) -> 'KOQuestions':
        """Create KOQuestions from a list of KOQuestion objects"""
        return cls(ko_questions=questions)

    def to_question_list(self) -> List[KOQuestion]:
        """Get the list of KOQuestion objects"""
        return self.ko_questions

    def get_by_title(self, title: str) -> Optional[KOQuestion]:
        return next((q for q in self.ko_questions if q.title == title), None)

    def get_next_by_title(self, title: str) -> Optional[KOQuestion]:
        for idx, q in enumerate(self.ko_questions):
            if q.title == title:
                return self.ko_questions[idx + 1] if idx + 1 < len(self.ko_questions) else None
        return None