# Complete PYOMO implementation

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

def race_track_optimization():
    """Optimize the number of races to maximize spectators"""

    # 1. MODEL CREATION
    model = pyo.ConcreteModel()

    # 2. DATA SETUP
    seating = [5000, 10000, 15000]
    max_spectators = [4500, 9500, 14500]
    total_races_limit = 10

    # CRITICAL: Validate array lengths before indexing
    assert len(seating) == len(max_spectators), "Array length mismatch"

    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.RangeSet(1, len(seating))  # 1-based indexing

    # 4. PARAMETERS (data containers)
    model.seating = pyo.Param(model.I, initialize={i+1: seating[i] for i in range(len(seating))})
    model.max_spectators = pyo.Param(model.I, initialize={i+1: max_spectators[i] for i in range(len(max_spectators))})

    # 5. VARIABLES
    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

    # Total races constraint
    def total_races_rule(model):
        return sum(model.x[i] for i in model.I) <= total_races_limit
    model.total_races_constraint = pyo.Constraint(rule=total_races_rule)

    # Spectator capacity constraints
    def spectator_capacity_rule(model, i):
        return model.seating[i] * model.x[i] <= model.max_spectators[i]
    model.spectator_capacity_constraint = pyo.Constraint(model.I, rule=spectator_capacity_rule)

    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')

    # Solve the model
    results = solver.solve(model, tee=True)

    # 9. RESULT PROCESSING
    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.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {x_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

# Run the optimization
race_track_optimization()