"""Choose items with maximum value while staying within a weight limit."""

from alleria import solve_model


weights = [2, 3, 4, 5]
values = [3, 4, 5, 8]
model = {
    "name": "knapsack",
    "objective_sense": "maximize",
    "columns": [
        {
            "name": f"item_{i}",
            "lower_bound": 0.0,
            "upper_bound": 1.0,
            "obj_coeff": value,
            "col_type": "binary",
        }
        for i, value in enumerate(values)
    ],
    "constraints": [
        {
            "name": "weight_limit",
            "sense": "<=",
            "rhs": 7.0,
            "coeffs": [[i, weight] for i, weight in enumerate(weights)],
        },
    ],
}

result = solve_model(
    model, backend="inprocess", preset="exact", include_primal=True
)
print(f"status: {result.status}")
if result.status != "optimal" or result.incumbent_primal is None:
    raise RuntimeError("This small example should have an optimal solution.")
print(f"objective: {result.objective:g}")
chosen = [
    name
    for name, value in zip(result.column_names, result.incumbent_primal)
    if value > 0.5
]
print(f"chosen: {', '.join(chosen)}")
