# Complete PYOMO implementation

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

def game_injury_optimization():
    """Optimization for scheduling games to maximize attendance and minimize injury risk."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Assuming these are the given data from the database
    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
    
    # Validate array lengths
    n_stadiums = len(average_attendance)
    n_games = len(injury_risks)
    assert len(capacity_percentage) == n_stadiums, "Array length mismatch for stadium data"
    assert len(home_games) == n_stadiums, "Array length mismatch for home games data"
    
    # 3. SETS
    model.J = pyo.RangeSet(1, n_stadiums)  # Stadiums
    model.I = pyo.RangeSet(1, n_games)     # Games
    
    # 4. PARAMETERS
    model.Average_Attendance = pyo.Param(model.J, initialize={j+1: average_attendance[j] for j in range(n_stadiums)})
    model.Capacity_Percentage = pyo.Param(model.J, initialize={j+1: capacity_percentage[j] for j in range(n_stadiums)})
    model.Risk = pyo.Param(model.I, initialize={i+1: injury_risks[i] for i in range(n_games)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.Binary)  # Game scheduling
    model.y = pyo.Var(model.J, within=pyo.NonNegativeIntegers)  # Home games at each stadium
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.Average_Attendance[j] * model.y[j] for j in model.J) - sum(model.Risk[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    # Total number of home games constraint
    def total_home_games_rule(model):
        return sum(model.y[j] for j in model.J) <= total_home_games_limit
    model.total_home_games_constraint = pyo.Constraint(rule=total_home_games_rule)
    
    # Cumulative injury risk constraint
    def injury_risk_rule(model):
        return sum(model.Risk[i] * model.x[i] for i in model.I) <= max_allowable_injury_risk
    model.injury_risk_constraint = pyo.Constraint(rule=injury_risk_rule)
    
    # Stadium capacity constraint
    def capacity_rule(model, j):
        return model.y[j] <= model.Capacity_Percentage[j] * total_home_games_limit
    model.capacity_constraint = pyo.Constraint(model.J, rule=capacity_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 j in model.J:
            y_val = pyo.value(model.y[j])
            print(f"y[{j}] = {int(y_val)}")
        
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {int(x_val)}")
        
    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
game_injury_optimization()