# Complete PYOMO implementation - Retry Attempt 4

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

def ship_mission_optimization():
    """Optimize ship assignments to missions to minimize operational costs."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Ship data
    ships = [1, 2, 3]
    tonnage = {1: 1500.0, 2: 2500.0, 3: 1800.0}
    cost_per_knot = {1: 11.0, 2: 13.0, 3: 12.0}
    cost_per_ton = {1: 5.5, 2: 6.0, 3: 5.8}
    
    # Mission data
    missions = [101, 102, 103]
    
    # 3. SETS
    model.Ships = pyo.Set(initialize=ships)
    model.Missions = pyo.Set(initialize=missions)
    
    # 4. PARAMETERS
    model.Tonnage = pyo.Param(model.Ships, initialize=tonnage)
    model.CostPerKnot = pyo.Param(model.Ships, initialize=cost_per_knot)
    model.CostPerTon = pyo.Param(model.Ships, initialize=cost_per_ton)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.Ships, model.Missions, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum((model.CostPerKnot[i] + model.Tonnage[i] * model.CostPerTon[i]) * model.x[i, j]
                   for i in model.Ships for j in model.Missions)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Each mission must be covered by exactly one ship
    def mission_coverage_rule(model, j):
        return sum(model.x[i, j] for i in model.Ships) == 1
    model.mission_coverage = pyo.Constraint(model.Missions, rule=mission_coverage_rule)
    
    # Each ship can be assigned to at most one mission
    def ship_assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.Missions) <= 1
    model.ship_assignment = pyo.Constraint(model.Ships, rule=ship_assignment_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # 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 ships to missions:")
        for i in model.Ships:
            for j in model.Missions:
                if pyo.value(model.x[i, j]) > 0.5:  # Binary variable, check if assigned
                    print(f"Ship {i} assigned to Mission {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
ship_mission_optimization()