import random

from app.schemas.grade_1.compose_and_decompose_numbers import (
    ComposeAndDecomposeNumbersProblem,
    DecompositionRow,
    PictureAsset,
)


def compose_and_decompose_numbers(
    picture: dict,
    whole: int = 10,
    randomize_rows: bool = False,
    seed: int | None = None,
) -> dict:
    """Generate number decomposition rows for one picture asset."""
    if whole < 2:
        raise ValueError("whole must be at least 2")

    selected_picture = PictureAsset.model_validate(picture)
    pairs = [(first_part, whole - first_part) for first_part in range(whole - 1, 0, -1)]

    if randomize_rows:
        rng = random.Random(seed)
        rng.shuffle(pairs)

    problem = ComposeAndDecomposeNumbersProblem(
        whole=whole,
        picture=selected_picture,
        rows=[
            DecompositionRow(
                position=index + 1,
                whole=whole,
                first_part=first_part,
                second_part=second_part,
                picture=selected_picture,
            )
            for index, (first_part, second_part) in enumerate(pairs)
        ],
    )

    return problem.model_dump()
