from langchain_core.output_parsers import BaseOutputParser


class BooleanOutputParser(BaseOutputParser[bool]):
    """Parse the output of an LLM call to a boolean."""

    true_val: str = "YES"
    """The string value that should be parsed as True."""
    false_val: str = "NO"
    """The string value that should be parsed as False."""

    def parse(self, text: str) -> bool:
        """Parse the output of an LLM call to a boolean.

        Args:
            text: output of a language model

        Returns:
            boolean

        """
        cleaned_upper_text = text.strip().upper()
        if (
            self.true_val.upper() in cleaned_upper_text
            and self.false_val.upper() in cleaned_upper_text
        ):
            raise ValueError(
                f"Ambiguous response. Both {self.true_val} and {self.false_val} in "
                f"received: {text}."
            )
        elif self.true_val.upper() in cleaned_upper_text:
            return True
        elif self.false_val.upper() in cleaned_upper_text:
            return False
        else:
            raise ValueError(
                f"BooleanOutputParser expected output value to include either "
                f"{self.true_val} or {self.false_val}. Received {text}."
            )

    @property
    def _type(self) -> str:
        """Snake-case string identifier for an output parser type."""
        return "boolean_output_parser"
