# Complete PYOMO implementation - Retry Attempt 4

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

def pilot_assignment_optimization():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    pilots = [1, 2, 3]
    aircraft = [101, 102, 103]
    
    cost_coefficients = {
        (1, 101): 2.55,
        (2, 102): 3.4,
        (3, 103): 4.25
    }
    
    pilot_qualifications = {
        (1, 101): 1,
        (2, 102): 1,
        (3, 103): 0
    }
    
    # CRITICAL: Validate array lengths before indexing
    assert all((p, a) in cost_coefficients for p in pilots for a in aircraft), "Missing cost coefficients"
    assert all((p, a) in pilot_qualifications for p in pilots for a in aircraft), "Missing pilot qualifications"
    
    # 3. SETS
    model.P = pyo.Set(initialize=pilots)
    model.A = pyo.Set(initialize=aircraft)
    
    # 4. PARAMETERS
    model.cost = pyo.Param(model.P, model.A, initialize=cost_coefficients)
    model.qualification = pyo.Param(model.P, model.A, initialize=pilot_qualifications)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.P, model.A, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.cost[p, a] * model.x[p, a] for p in model.P for a in model.A)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Pilot Assignment Limit
    def pilot_limit_rule(model, p):
        return sum(model.x[p, a] for a in model.A) <= 1
    model.pilot_limit = pyo.Constraint(model.P, rule=pilot_limit_rule)
    
    # Aircraft Assignment Requirement
    def aircraft_requirement_rule(model, a):
        return sum(model.x[p, a] for p in model.P) == 1
    model.aircraft_requirement = pyo.Constraint(model.A, rule=aircraft_requirement_rule)
    
    # Pilot Qualifications
    def qualification_rule(model, p, a):
        return model.x[p, a] <= model.qualification[p, a]
    model.qualification_constraint = pyo.Constraint(model.P, model.A, rule=qualification_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 p in model.P:
            for a in model.A:
                if pyo.value(model.x[p, a]) > 0:
                    print(f"x[{p}, {a}] = {pyo.value(model.x[p, a])}")
        
    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__":
    pilot_assignment_optimization()