import random

from app.schemas.grade_1.where_are_more_items import (
    ItemGroup,
    MoreItemsComparison,
    PictureAsset,
    WhereAreMoreItemsProblem,
)


def where_are_more_items(
    available_pictures: list[dict],
    comparison_count: int = 3,
    min_quantity: int = 1,
    max_quantity: int = 10,
    seed: int | None = None,
) -> dict:
    """Generate comparison cards where students choose the group with more items."""
    pictures = [PictureAsset.model_validate(picture) for picture in available_pictures]

    if len(pictures) < 2:
        raise ValueError("available_pictures must contain at least 2 pictures")

    if min_quantity >= max_quantity:
        raise ValueError("max_quantity must be greater than min_quantity")

    rng = random.Random(seed)
    quantity_values = list(range(min_quantity, max_quantity + 1))
    comparisons: list[MoreItemsComparison] = []

    for index in range(comparison_count):
        left_picture, right_picture = rng.sample(pictures, 2)
        left_quantity, right_quantity = rng.sample(quantity_values, 2)
        answer_side = "left" if left_quantity > right_quantity else "right"

        comparisons.append(
            MoreItemsComparison(
                position=index + 1,
                left_group=ItemGroup(
                    side="left",
                    picture=left_picture,
                    quantity=left_quantity,
                ),
                right_group=ItemGroup(
                    side="right",
                    picture=right_picture,
                    quantity=right_quantity,
                ),
                answer_side=answer_side,
            )
        )

    problem = WhereAreMoreItemsProblem(comparisons=comparisons)

    return problem.model_dump()
