# Complete DOCPLEX implementation - Retry Attempt 4

from docplex.mp.model import Model

def optimize_casting():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="musical_casting")

    # Data from the problem context
    actor_ages = {101: 25, 102: 30, 103: 35}
    musical_requirements = {1: 3, 2: 4, 3: 5}

    # Actors and musicals
    actors = list(actor_ages.keys())
    musicals = list(musical_requirements.keys())

    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(actors) > 0 and len(musicals) > 0, "Actors or musicals data is missing"

    # 2. VARIABLES
    # Binary decision variables for actor assignments
    x = {(i, j): mdl.binary_var(name=f"x_{i}_{j}") for i in actors for j in musicals}

    # 3. OBJECTIVE FUNCTION
    # Minimize the total age of the actors assigned to the musicals
    objective = mdl.sum(actor_ages[i] * x[i, j] for i in actors for j in musicals)
    mdl.minimize(objective)

    # 4. CONSTRAINTS
    # Musical requirements: Each musical must have exactly the number of actors it requires
    for j in musicals:
        mdl.add_constraint(mdl.sum(x[i, j] for i in actors) == musical_requirements[j], ctname=f"musical_req_{j}")

    # Actor assignment: Each actor can only be assigned to one musical
    for i in actors:
        mdl.add_constraint(mdl.sum(x[i, j] for j in musicals) <= 1, ctname=f"actor_assign_{i}")

    # 5. SOLVING & RESULTS
    solution = mdl.solve()

    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in actors:
            for j in musicals:
                if solution.get_value(x[i, j]) > 0.5:  # Binary variable threshold
                    print(f"Actor {i} is assigned to musical {j}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

    return mdl

# Run the optimization
optimize_casting()