# Complete PYOMO implementation

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

def railway_optimization():
    """Optimize train allocation to minimize operational costs"""

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

    # 2. DATA SETUP
    railways = [1, 2, 3]
    operational_costs = {1: 120.0, 2: 180.0, 3: 140.0}
    capacities = {1: 12, 2: 18, 3: 15}
    minimum_trains_required = {1: 3, 2: 4, 3: 5}
    total_trains_available = 30

    # CRITICAL: Validate array lengths before indexing
    assert len(operational_costs) == len(capacities) == len(minimum_trains_required) == len(railways), "Array length mismatch"

    # 3. SETS
    model.R = pyo.Set(initialize=railways)

    # 4. PARAMETERS
    model.operational_cost = pyo.Param(model.R, initialize=operational_costs)
    model.capacity = pyo.Param(model.R, initialize=capacities)
    model.minimum_trains = pyo.Param(model.R, initialize=minimum_trains_required)

    # 5. VARIABLES
    model.x = pyo.Var(model.R, within=pyo.NonNegativeIntegers)

    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.operational_cost[r] * model.x[r] for r in model.R)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)

    # 7. CONSTRAINTS

    # Total train availability constraint
    def total_trains_rule(model):
        return sum(model.x[r] for r in model.R) <= total_trains_available
    model.total_trains_constraint = pyo.Constraint(rule=total_trains_rule)

    # Railway capacity constraints
    def capacity_rule(model, r):
        return model.x[r] <= model.capacity[r]
    model.capacity_constraint = pyo.Constraint(model.R, rule=capacity_rule)

    # Minimum train requirement constraints
    def minimum_trains_rule(model, r):
        return model.x[r] >= model.minimum_trains[r]
    model.minimum_trains_constraint = pyo.Constraint(model.R, rule=minimum_trains_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)

    # 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 r in model.R:
            x_val = pyo.value(model.x[r])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{r}] = {x_val:.0f}")

    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
railway_optimization()