#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Game Injury Optimization Problem
"""

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

def game_injury_optimization():
    """Optimization model to minimize total injury risk while meeting stadium capacity and attendance constraints."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data (replace with actual data loading logic)
    games = [1, 2, 3]
    stadiums = [1, 2, 3]
    
    injury_risk = {1: 0.15, 2: 0.1, 3: 0.2}
    stadium_capacity = {1: 0.85, 2: 0.9, 3: 0.8}
    average_attendance = {1: 5500, 2: 6000, 3: 5000}
    
    # Validate array lengths
    assert len(games) == len(injury_risk), "Mismatch in games and injury risk data"
    assert len(stadiums) == len(stadium_capacity) == len(average_attendance), "Mismatch in stadium data"
    
    # 3. SETS
    model.G = pyo.Set(initialize=games)  # Set of games
    model.S = pyo.Set(initialize=stadiums)  # Set of stadiums
    
    # 4. PARAMETERS
    model.risk_value = pyo.Param(model.G, initialize=injury_risk)
    model.capacity_percentage = pyo.Param(model.S, initialize=stadium_capacity)
    model.average_attendance = pyo.Param(model.S, initialize=average_attendance)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.G, within=pyo.Binary)  # Binary decision variable for game scheduling
    model.y = pyo.Var(model.S, within=pyo.NonNegativeReals, bounds=(0, 1))  # Continuous decision variable for stadium usage
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.risk_value[i] * model.x[i] for i in model.G)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Stadium Capacity Constraint
    def capacity_rule(model, j):
        return sum(model.x[i] for i in model.G) * model.capacity_percentage[j] <= model.y[j] * model.capacity_percentage[j]
    model.capacity_constraint = pyo.Constraint(model.S, rule=capacity_rule)
    
    # Minimum Attendance Constraint
    def attendance_rule(model, j):
        return sum(model.x[i] for i in model.G) * model.average_attendance[j] >= model.average_attendance[j]
    model.attendance_constraint = pyo.Constraint(model.S, rule=attendance_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)  # tee=True shows solver output
    
    # 9. RESULT PROCESSING
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nVariable values:")
        for i in model.G:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {int(x_val)}")
        
        for j in model.S:
            y_val = pyo.value(model.y[j])
            print(f"y[{j}] = {y_val:.3f}")
        
    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

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