# Complete PYOMO implementation

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

def roller_coaster_optimization():
    """Optimize maintenance hours allocation for roller coasters to minimize downtime."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Data from the problem statement
    roller_coaster_ids = [1, 2, 3]
    downtime_coefficients = {1: 0.4, 2: 0.35, 3: 0.25}
    minimum_hours = {1: 3.0, 2: 4.0, 3: 2.5}
    maximum_hours = {1: 10.0, 2: 12.0, 3: 9.0}
    total_available_hours = 22
    
    # CRITICAL: Validate array lengths before indexing
    assert len(roller_coaster_ids) == len(downtime_coefficients) == len(minimum_hours) == len(maximum_hours), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=roller_coaster_ids)
    
    # 4. PARAMETERS
    model.downtime_coefficient = pyo.Param(model.I, initialize=downtime_coefficients)
    model.minimum_hours = pyo.Param(model.I, initialize=minimum_hours)
    model.maximum_hours = pyo.Param(model.I, initialize=maximum_hours)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.downtime_coefficient[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Total maintenance hours constraint
    def total_hours_rule(model):
        return sum(model.x[i] for i in model.I) <= total_available_hours
    model.total_hours_constraint = pyo.Constraint(rule=total_hours_rule)
    
    # Minimum maintenance hours constraint
    def min_hours_rule(model, i):
        return model.x[i] >= model.minimum_hours[i]
    model.min_hours_constraint = pyo.Constraint(model.I, rule=min_hours_rule)
    
    # Maximum maintenance hours constraint
    def max_hours_rule(model, i):
        return model.x[i] <= model.maximum_hours[i]
    model.max_hours_constraint = pyo.Constraint(model.I, rule=max_hours_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Solve the model
    results = solver.solve(model, tee=True)
    
    # 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):.3f}")
        
        # 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

# Execute the optimization
roller_coaster_optimization()