# Complete PYOMO implementation

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

def pilot_record_optimization():
    """Optimize pilot flight assignments to minimize total flights"""

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

    # 2. DATA SETUP
    pilots = [1, 2, 3]
    aircrafts = [101, 102, 103]
    min_flights = {1: 10, 2: 15, 3: 12}
    max_flights = {101: 120, 102: 100, 103: 110}

    # CRITICAL: Validate data lengths before indexing
    assert len(min_flights) == len(pilots), "Mismatch in pilots and min_flights data"
    assert len(max_flights) == len(aircrafts), "Mismatch in aircrafts and max_flights data"

    # 3. SETS
    model.P = pyo.Set(initialize=pilots)
    model.A = pyo.Set(initialize=aircrafts)

    # 4. PARAMETERS
    model.min_flights = pyo.Param(model.P, initialize=min_flights)
    model.max_flights = pyo.Param(model.A, initialize=max_flights)

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

    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.x[i, j] for i in model.P for j in model.A)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)

    # 7. CONSTRAINTS

    # Pilot Minimum Flight Requirement
    def pilot_min_flights_rule(model, i):
        return sum(model.x[i, j] for j in model.A) >= model.min_flights[i]
    model.pilot_min_flights_constraint = pyo.Constraint(model.P, rule=pilot_min_flights_rule)

    # Aircraft Maximum Flight Capacity
    def aircraft_max_flights_rule(model, j):
        return sum(model.x[i, j] for i in model.P) <= model.max_flights[j]
    model.aircraft_max_flights_constraint = pyo.Constraint(model.A, rule=aircraft_max_flights_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
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")

        # Extract variable values
        print("\nFlight assignments:")
        for i in model.P:
            for j in model.A:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0:  # Only print non-zero values
                    print(f"Flights assigned to pilot {i} for aircraft {j}: {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

# Run the optimization
pilot_record_optimization()