import unittest

from math_problems_structure.grade_1 import join_corresponding_sums


class JoinCorrespondingSumsTest(unittest.TestCase):
    def test_creates_problem_with_matching_sums(self) -> None:
        problem = join_corresponding_sums(pair_count=3, seed=1)

        self.assertEqual(problem["instructions"], "Conecta.")
        self.assertEqual(len(problem["left_expressions"]), 3)
        self.assertEqual(len(problem["right_expressions"]), 3)
        self.assertEqual(len(problem["answer_key"]), 3)

        left_by_position = {
            expression["position"]: expression
            for expression in problem["left_expressions"]
        }
        right_by_position = {
            expression["position"]: expression
            for expression in problem["right_expressions"]
        }

        for expression in problem["left_expressions"] + problem["right_expressions"]:
            self.assertEqual(
                expression["first_addend"] + expression["second_addend"],
                expression["total"],
            )

        for connection in problem["answer_key"]:
            left_expression = left_by_position[connection["left_position"]]
            right_expression = right_by_position[connection["right_position"]]

            self.assertEqual(left_expression["total"], right_expression["total"])
            self.assertEqual(left_expression["total"], connection["total"])
            self.assertEqual(left_expression["match_id"], right_expression["match_id"])
            self.assertEqual(left_expression["match_id"], connection["match_id"])

    def test_raises_for_impossible_ranges(self) -> None:
        with self.assertRaisesRegex(
            ValueError,
            "sum and addend ranges must contain enough matchable sums",
        ):
            join_corresponding_sums(pair_count=3, min_sum=2, max_sum=2)


if __name__ == "__main__":
    unittest.main()
