# Complete PYOMO implementation

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

def ship_optimization():
    """Optimize captain assignments to ships to minimize total age"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    captains = [1, 2, 3]
    ships = [101, 102, 103]
    ages = {1: 45, 2: 50, 3: 55}
    
    # CRITICAL: Validate array lengths before indexing
    assert len(captains) == len(ages), "Array length mismatch for captains and ages"
    
    # 3. SETS
    model.C = pyo.Set(initialize=captains)
    model.S = pyo.Set(initialize=ships)
    
    # 4. PARAMETERS
    model.age = pyo.Param(model.C, initialize=ages)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.C, model.S, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.age[i] * model.x[i, j] for i in model.C for j in model.S)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Each captain is assigned to exactly one ship
    def captain_assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.S) == 1
    model.captain_assignment = pyo.Constraint(model.C, rule=captain_assignment_rule)
    
    # Each ship has exactly one captain
    def ship_assignment_rule(model, j):
        return sum(model.x[i, j] for i in model.C) == 1
    model.ship_assignment = pyo.Constraint(model.S, rule=ship_assignment_rule)
    
    # Only eligible captains (age ≤ 60) can be assigned
    def eligibility_rule(model, i, j):
        if model.age[i] > 60:
            return model.x[i, j] == 0
        else:
            return pyo.Constraint.Skip
    model.eligibility = pyo.Constraint(model.C, model.S, rule=eligibility_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("\nAssignment of captains to ships:")
        for i in model.C:
            for j in model.S:
                if pyo.value(model.x[i, j]) > 0.5:  # Binary variable, check if assigned
                    print(f"Captain {i} assigned to Ship {j}")
        
    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
ship_optimization()