# Complete PYOMO implementation - Retry Attempt 4

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

def optimize_flight_assignment():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Define airlines and routes
    airlines = [1, 2, 3]
    routes = [1, 2, 3]
    
    # Cost data from cost_airline_route table
    cost_data = {
        (1, 1): 1200.0,
        (1, 2): 1800.0,
        (1, 3): 2500.0
    }
    
    # Capacity data from capacity_airline table
    capacity_data = {
        1: 8,
        2: 12,
        3: 6
    }
    
    # Validate array lengths
    assert len(cost_data) == len(airlines) * len(routes), "Cost data length mismatch"
    assert len(capacity_data) == len(airlines), "Capacity data length mismatch"
    
    # 3. SETS
    model.A = pyo.Set(initialize=airlines)
    model.R = pyo.Set(initialize=routes)
    
    # 4. PARAMETERS
    model.cost = pyo.Param(model.A, model.R, initialize=cost_data)
    model.capacity = pyo.Param(model.A, initialize=capacity_data)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.A, model.R, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.cost[a, r] * model.x[a, r] for a in model.A for r in model.R)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Route Coverage: Each route must be assigned to exactly one airline
    def route_coverage_rule(model, r):
        return sum(model.x[a, r] for a in model.A) == 1
    model.route_coverage = pyo.Constraint(model.R, rule=route_coverage_rule)
    
    # Airline Capacity: No airline can be assigned more routes than its capacity
    def airline_capacity_rule(model, a):
        return sum(model.x[a, r] for r in model.R) <= model.capacity[a]
    model.airline_capacity = pyo.Constraint(model.A, rule=airline_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 a in model.A:
            for r in model.R:
                x_val = pyo.value(model.x[a, r])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{a}, {r}] = {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__":
    optimize_flight_assignment()