# Complete PYOMO implementation - Retry Attempt 4

import pyomo.environ as pyo
from pyomo.opt import SolverFactory

def optimize_casting():
    """Optimize the casting process for musicals to minimize total age of the cast."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the problem description
    actor_ids = [101, 102, 103, 104, 105]
    musical_ids = [1, 2, 3]
    ages = {101: 25, 102: 30, 103: 35, 104: 28, 105: 32}
    required_actors = {1: 3, 2: 4, 3: 5}
    
    # CRITICAL: Validate data consistency
    assert all(actor_id in ages for actor_id in actor_ids), "Missing age data for some actors"
    assert all(musical_id in required_actors for musical_id in musical_ids), "Missing requirement data for some musicals"
    
    # 3. SETS
    model.Actors = pyo.Set(initialize=actor_ids)
    model.Musicals = pyo.Set(initialize=musical_ids)
    
    # 4. PARAMETERS
    model.age = pyo.Param(model.Actors, initialize=ages)
    model.required_actors = pyo.Param(model.Musicals, initialize=required_actors)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.Actors, model.Musicals, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.age[i] * model.x[i, j] for i in model.Actors for j in model.Musicals)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Musical Requirements Constraint
    def musical_requirement_rule(model, j):
        return sum(model.x[i, j] for i in model.Actors) == model.required_actors[j]
    model.musical_requirement = pyo.Constraint(model.Musicals, rule=musical_requirement_rule)
    
    # Actor Assignment Constraint
    def actor_assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.Musicals) <= 1
    model.actor_assignment = pyo.Constraint(model.Actors, rule=actor_assignment_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap
    
    # Solve the model
    results = solver.solve(model, tee=True)
    
    # 9. RESULT PROCESSING
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nAssignment of actors to musicals:")
        for i in model.Actors:
            for j in model.Musicals:
                if pyo.value(model.x[i, j]) > 0.5:  # Binary variable, check if assigned
                    print(f"Actor {i} assigned to Musical {j}")
        
    elif results.solver.termination_condition == pyo.TerminationCondition.infeasible:
        print("Problem is infeasible")
    elif results.solver.termination_condition == pyo.TerminationCondition.unbounded:
        print("Problem is unbounded")
    else:
        print(f"Solver terminated with condition: {results.solver.termination_condition}")
    
    return model

# Run the optimization
optimize_casting()