#!/usr/bin/env python3
"""
Gurobipy 12.0.2 Implementation for Game Injury Optimization Problem
"""

import gurobipy as gp
from gurobipy import GRB

def game_injury_optimization():
    """Optimization model to minimize total injury risk across scheduled games."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("game_injury_optimization")
    
    # Sample data from the problem description
    injury_risk = {1: 0.15, 2: 0.1, 3: 0.2}
    game_scheduling = {1: True, 2: False, 3: True}
    stadium_usage = {1: 0.75, 2: 0.8, 3: 0.7}
    stadium = {
        1: {'capacity_percentage': 0.85, 'average_attendance': 5500},
        2: {'capacity_percentage': 0.9, 'average_attendance': 6000},
        3: {'capacity_percentage': 0.8, 'average_attendance': 5000}
    }
    
    # CRITICAL: Validate array lengths before loops
    assert len(injury_risk) == len(game_scheduling), "Array length mismatch for injury_risk and game_scheduling"
    assert len(stadium_usage) == len(stadium), "Array length mismatch for stadium_usage and stadium"
    
    # 2. VARIABLES
    # Binary decision variables for game scheduling
    x = {i: model.addVar(vtype=GRB.BINARY, name=f"x_{i}") for i in injury_risk.keys()}
    
    # Continuous decision variables for stadium usage
    y = {j: model.addVar(vtype=GRB.CONTINUOUS, name=f"y_{j}", lb=0, ub=1) for j in stadium_usage.keys()}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize total injury risk across all scheduled games
    model.setObjective(gp.quicksum(injury_risk[i] * x[i] for i in injury_risk.keys()), GRB.MINIMIZE)
    
    # 4. CONSTRAINTS
    # Stadium Capacity Constraint
    for j in stadium.keys():
        model.addConstr(
            gp.quicksum(x[i] * stadium[j]['capacity_percentage'] for i in injury_risk.keys()) <= y[j] * stadium[j]['capacity_percentage'],
            name=f"stadium_capacity_{j}"
        )
    
    # Minimum Attendance Constraint
    for j in stadium.keys():
        model.addConstr(
            gp.quicksum(x[i] * stadium[j]['average_attendance'] for i in injury_risk.keys()) >= stadium[j]['average_attendance'],
            name=f"min_attendance_{j}"
        )
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in injury_risk.keys():
            if x[i].x > 1e-6:
                print(f"Game {i} is scheduled: {x[i].x:.0f}")
        for j in stadium_usage.keys():
            print(f"Stadium {j} usage percentage: {y[j].x:.2f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Execute the optimization model
if __name__ == "__main__":
    game_injury_optimization()