# Complete PYOMO implementation - Retry Attempt 4

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

def optimize_ship_captain_assignment():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()

    # 2. DATA SETUP
    captains = [1, 2, 3]
    ships = [1, 2, 3]

    # Cost coefficients
    cost_coefficients = {
        (1, 1): 1200,
        (2, 2): 1500,
        (3, 3): 1000
    }

    # Compatibility rules
    compatibility_rules = {
        (1, 1): True,
        (2, 2): True,
        (3, 3): True
    }

    # Age rules
    age_rules = {
        (1, 1): True,
        (2, 2): True,
        (3, 3): True
    }

    # 3. SETS
    model.Captains = pyo.Set(initialize=captains)
    model.Ships = pyo.Set(initialize=ships)

    # 4. PARAMETERS
    model.cost_coefficients = pyo.Param(model.Captains, model.Ships, initialize=cost_coefficients)
    model.compatibility_rules = pyo.Param(model.Captains, model.Ships, initialize=compatibility_rules)
    model.age_rules = pyo.Param(model.Captains, model.Ships, initialize=age_rules)

    # 5. VARIABLES
    model.x = pyo.Var(model.Captains, model.Ships, within=pyo.Binary)

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

    # 7. CONSTRAINTS

    # Ship Assignment Constraint
    def ship_assignment_rule(model, j):
        return sum(model.x[i, j] for i in model.Captains) == 1
    model.ship_assignment = pyo.Constraint(model.Ships, rule=ship_assignment_rule)

    # Captain Assignment Constraint
    def captain_assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.Ships) <= 1
    model.captain_assignment = pyo.Constraint(model.Captains, rule=captain_assignment_rule)

    # Compatibility Constraint
    def compatibility_rule(model, i, j):
        return model.x[i, j] <= model.compatibility_rules[i, j]
    model.compatibility = pyo.Constraint(model.Captains, model.Ships, rule=compatibility_rule)

    # Age Constraint
    def age_rule(model, i, j):
        return model.x[i, j] <= model.age_rules[i, j]
    model.age = pyo.Constraint(model.Captains, model.Ships, rule=age_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 i in model.Captains:
            for j in model.Ships:
                if pyo.value(model.x[i, j]) > 0:
                    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

# Execute the optimization
optimize_ship_captain_assignment()