# Complete GUROBIPY implementation

import gurobipy as gp
from gurobipy import GRB

def optimize_game_injury():
    """Optimize game scheduling to maximize attendance and minimize injury risk."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("game_injury")
    
    # Data from the database
    average_attendance = [8000, 12000, 15000]
    capacity_percentage = [0.85, 0.9, 0.95]
    home_games = [6, 8, 6]
    injury_risk = [0.02, 0.03, 0.04, 0.01, 0.05]
    scheduled = [True, False, True, False, True]
    
    # Parameters
    total_home_games_limit = 20
    max_allowable_injury_risk = 0.1
    
    # Validate array lengths
    n_stadiums = len(average_attendance)
    n_games = len(injury_risk)
    assert len(capacity_percentage) == n_stadiums, "Array length mismatch for stadiums"
    assert len(home_games) == n_stadiums, "Array length mismatch for home games"
    assert len(scheduled) == n_games, "Array length mismatch for games"
    
    # 2. VARIABLES
    x = {i: model.addVar(vtype=GRB.BINARY, name=f"x_{i}") for i in range(n_games)}
    y = {j: model.addVar(vtype=GRB.INTEGER, name=f"y_{j}", lb=0) for j in range(n_stadiums)}
    
    # 3. OBJECTIVE FUNCTION
    model.setObjective(
        gp.quicksum(average_attendance[j] * y[j] for j in range(n_stadiums)) -
        gp.quicksum(injury_risk[i] * x[i] for i in range(n_games)),
        GRB.MAXIMIZE
    )
    
    # 4. CONSTRAINTS
    # Total number of home games scheduled across all stadiums
    model.addConstr(gp.quicksum(y[j] for j in range(n_stadiums)) <= total_home_games_limit, name="total_home_games_limit")
    
    # Cumulative injury risk
    model.addConstr(gp.quicksum(injury_risk[i] * x[i] for i in range(n_games)) <= max_allowable_injury_risk, name="max_injury_risk")
    
    # Stadium capacity constraints
    for j in range(n_stadiums):
        model.addConstr(y[j] <= capacity_percentage[j] * total_home_games_limit, name=f"capacity_{j}")
    
    # Each game can only be scheduled once
    for i in range(n_games):
        model.addConstr(x[i] <= 1, name=f"schedule_once_{i}")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for j in range(n_stadiums):
            if y[j].x > 1e-6:
                print(f"Home games at stadium {j}: {y[j].x:.0f}")
        for i in range(n_games):
            if x[i].x > 1e-6:
                print(f"Game {i} scheduled: {x[i].x:.0f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Run the optimization
optimize_game_injury()