# Complete PYOMO implementation - Retry Attempt 4

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

def train_station_optimization():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Define sets for trains and stations
    trains = [1, 2, 3]
    stations = [1, 2, 3]
    
    # Define parameters
    passenger_count = {
        (1, 1): 150,
        (2, 2): 100,
        (3, 3): 50
    }
    
    waiting_time = {
        (1, 1): 5,
        (2, 2): 10,
        (3, 3): 15
    }
    
    number_of_platforms = {
        1: 4,
        2: 3,
        3: 2
    }
    
    # Validate array lengths before indexing
    for t in trains:
        for s in stations:
            assert (t, s) in passenger_count, f"Missing passenger_count for train {t} at station {s}"
            assert (t, s) in waiting_time, f"Missing waiting_time for train {t} at station {s}"
    
    for s in stations:
        assert s in number_of_platforms, f"Missing number_of_platforms for station {s}"
    
    # 3. SETS
    model.T = pyo.Set(initialize=trains)
    model.S = pyo.Set(initialize=stations)
    
    # 4. PARAMETERS
    model.passenger_count = pyo.Param(model.T, model.S, initialize=passenger_count)
    model.waiting_time = pyo.Param(model.T, model.S, initialize=waiting_time)
    model.number_of_platforms = pyo.Param(model.S, initialize=number_of_platforms)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.T, model.S, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.passenger_count[t, s] * model.waiting_time[t, s] * model.x[t, s] for t in model.T for s in model.S)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Platform Capacity Constraint
    def platform_capacity_rule(model, s):
        return sum(model.x[t, s] for t in model.T) <= model.number_of_platforms[s]
    model.platform_capacity_constraint = pyo.Constraint(model.S, rule=platform_capacity_rule)
    
    # Maximum Waiting Time Constraint
    def max_waiting_time_rule(model, t, s):
        return model.waiting_time[t, s] * model.x[t, s] <= 15
    model.max_waiting_time_constraint = pyo.Constraint(model.T, model.S, rule=max_waiting_time_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 t in model.T:
            for s in model.S:
                x_val = pyo.value(model.x[t, s])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{t}, {s}] = {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

# Execute the optimization
if __name__ == "__main__":
    train_station_optimization()