# Complete DOCPLEX implementation

from docplex.mp.model import Model

def game_injury_optimization():
    """Optimize game scheduling to maximize attendance and minimize injury risk."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="game_injury")
    
    # Data from the problem context
    average_attendance = [8000, 12000, 15000]
    capacity_percentage = [0.85, 0.9, 0.95]
    home_games = [6, 8, 6]
    injury_risks = [0.02, 0.03, 0.04, 0.01, 0.05]
    total_home_games_limit = 20
    max_allowable_injury_risk = 0.1
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(average_attendance) == len(capacity_percentage) == len(home_games), "Array length mismatch"
    safe_range_stadiums = range(len(average_attendance))
    safe_range_games = range(len(injury_risks))
    
    # 2. VARIABLES
    x = {i: mdl.binary_var(name=f"x_{i}") for i in safe_range_games}
    y = {j: mdl.integer_var(name=f"y_{j}", lb=0) for j in safe_range_stadiums}
    
    # 3. OBJECTIVE FUNCTION
    objective = mdl.sum(average_attendance[j] * y[j] for j in safe_range_stadiums) - mdl.sum(injury_risks[i] * x[i] for i in safe_range_games)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    # Total number of home games constraint
    mdl.add_constraint(mdl.sum(y[j] for j in safe_range_stadiums) <= total_home_games_limit, ctname="total_home_games_limit")
    
    # Cumulative injury risk constraint
    mdl.add_constraint(mdl.sum(injury_risks[i] * x[i] for i in safe_range_games) <= max_allowable_injury_risk, ctname="max_injury_risk")
    
    # Stadium capacity constraints
    for j in safe_range_stadiums:
        mdl.add_constraint(y[j] <= capacity_percentage[j] * total_home_games_limit, ctname=f"capacity_{j}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for j in safe_range_stadiums:
            print(f"Home games at stadium {j}: {solution.get_value(y[j])}")
        for i in safe_range_games:
            print(f"Game {i} scheduled: {solution.get_value(x[i])}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
game_injury_optimization()