# Complete PYOMO implementation

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

def railway_optimization():
    """Optimization model for assigning managers to railways."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Managers data
    managers = [1, 2, 3]
    cost_per_level = {1: 120, 2: 150, 3: 200}
    capacities = {1: 4, 2: 6, 3: 8}
    
    # Railways data
    railways = [1, 2, 3]
    
    # CRITICAL: Validate array lengths before indexing
    assert len(managers) == len(cost_per_level) == len(capacities), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.M = pyo.Set(initialize=managers)  # Set of managers
    model.R = pyo.Set(initialize=railways)  # Set of railways
    
    # 4. PARAMETERS (data containers)
    model.cost = pyo.Param(model.M, initialize=cost_per_level)
    model.capacity = pyo.Param(model.M, initialize=capacities)
    
    # 5. VARIABLES
    # Binary decision variables: x[m, r] = 1 if manager m is assigned to railway r
    model.x = pyo.Var(model.M, model.R, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    # Minimize the total cost of assigning managers to railways
    def obj_rule(model):
        return sum(model.cost[m] * model.x[m, r] for m in model.M for r in model.R)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Railway Management Constraint: Each railway must be managed by at least one manager
    def railway_management_rule(model, r):
        return sum(model.x[m, r] for m in model.M) >= 1
    model.railway_management_constraint = pyo.Constraint(model.R, rule=railway_management_rule)
    
    # Manager Capacity Constraint: No manager can be assigned to more railways than their capacity
    def manager_capacity_rule(model, m):
        return sum(model.x[m, r] for r in model.R) <= model.capacity[m]
    model.manager_capacity_constraint = pyo.Constraint(model.M, rule=manager_capacity_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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 m in model.M:
            for r in model.R:
                if pyo.value(model.x[m, r]) > 0.5:  # Only print assignments
                    print(f"Manager {m} is assigned to Railway {r}")
        
    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
if __name__ == "__main__":
    railway_optimization()