#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Race Track Optimization Problem
"""

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

def race_track_optimization():
    """Optimize the number of races at each track to maximize seating capacity utilization."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Seating capacities for each track
    seating_capacities = [5000, 10000, 15000]
    
    # Maximum number of races allowed per track
    max_races = [10, 12, 15]
    
    # Total available seating capacity (assumed value, replace with actual value if available)
    total_seating_capacity = 200000
    
    # Validate array lengths before indexing
    assert len(seating_capacities) == len(max_races), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.RangeSet(1, len(seating_capacities))  # 1-based indexing
    
    # 4. PARAMETERS (data containers)
    model.seating = pyo.Param(model.I, initialize={i+1: seating_capacities[i] for i in range(len(seating_capacities))})
    model.max_races = pyo.Param(model.I, initialize={i+1: max_races[i] for i in range(len(max_races))})
    model.total_capacity = pyo.Param(initialize=total_seating_capacity)
    
    # 5. VARIABLES
    # Number of races at each track
    model.x = pyo.Var(model.I, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.seating[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Race Limit per Track
    def race_limit_rule(model, i):
        return model.x[i] <= model.max_races[i]
    model.race_limit_constraint = pyo.Constraint(model.I, rule=race_limit_rule)
    
    # Total Seating Capacity
    def total_capacity_rule(model):
        return sum(model.seating[i] * model.x[i] for i in model.I) <= model.total_capacity
    model.total_capacity_constraint = pyo.Constraint(rule=total_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("\nNumber of races at each track:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            print(f"Track {i}: {int(x_val)} races")
        
    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__":
    race_track_optimization()