# Complete PYOMO implementation

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

def bike_optimization():
    """Bike-sharing system optimization using Pyomo"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    station_ids = [1, 2, 3]
    dock_counts = [15, 20, 10]
    expected_demands = [12, 18, 8]
    shortage_penalties = [5, 4, 6]  # Example penalties for shortages
    excess_penalties = [3, 2, 4]    # Example penalties for excesses
    total_bikes = 3  # Total number of bikes available in the system
    
    # CRITICAL: Validate array lengths before indexing
    assert len(station_ids) == len(dock_counts) == len(expected_demands) == len(shortage_penalties) == len(excess_penalties), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=station_ids)
    
    # 4. PARAMETERS
    model.dock_count = pyo.Param(model.I, initialize={station_ids[i]: dock_counts[i] for i in range(len(station_ids))})
    model.expected_demand = pyo.Param(model.I, initialize={station_ids[i]: expected_demands[i] for i in range(len(station_ids))})
    model.shortage_penalty = pyo.Param(model.I, initialize={station_ids[i]: shortage_penalties[i] for i in range(len(station_ids))})
    model.excess_penalty = pyo.Param(model.I, initialize={station_ids[i]: excess_penalties[i] for i in range(len(station_ids))})
    
    # 5. VARIABLES
    model.s = pyo.Var(model.I, within=pyo.NonNegativeReals)
    model.e = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.shortage_penalty[i] * model.s[i] + model.excess_penalty[i] * model.e[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Total Bikes Constraint
    def total_bikes_rule(model):
        return sum(model.s[i] + model.e[i] for i in model.I) == total_bikes
    model.total_bikes_constraint = pyo.Constraint(rule=total_bikes_rule)
    
    # Dock Capacity Constraints
    def dock_capacity_rule(model, i):
        return model.s[i] + model.expected_demand[i] <= model.dock_count[i]
    model.dock_capacity_constraint = pyo.Constraint(model.I, rule=dock_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 i in model.I:
            s_val = pyo.value(model.s[i])
            e_val = pyo.value(model.e[i])
            print(f"s[{i}] = {s_val:.3f}, e[{i}] = {e_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
bike_optimization()