# Complete PYOMO implementation - Retry Attempt 4

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

def naval_optimization():
    """Optimize ship assignments to minimize battle deaths."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the problem description
    ships = [1, 2, 3]
    battles = [101, 102, 103]
    deaths_data = {
        (1, 101): 15,
        (2, 102): 25,
        (3, 103): 5
    }
    min_ships_data = {
        101: 3,
        102: 5,
        103: 2
    }
    max_ships = 5  # Example maximum number of ships available
    
    # CRITICAL: Validate array lengths before indexing
    assert len(deaths_data) == len(ships) * len(battles), "Array length mismatch"
    
    # 3. SETS
    model.Ships = pyo.Set(initialize=ships)
    model.Battles = pyo.Set(initialize=battles)
    
    # 4. PARAMETERS
    model.deaths = pyo.Param(model.Ships, model.Battles, initialize=deaths_data, default=0)
    model.min_ships = pyo.Param(model.Battles, initialize=min_ships_data)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.Ships, model.Battles, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.deaths[i, j] * model.x[i, j] for i in model.Ships for j in model.Battles)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Each ship can be assigned to at most one battle
    def ship_assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.Battles) <= 1
    model.ship_assignment_constraint = pyo.Constraint(model.Ships, rule=ship_assignment_rule)
    
    # Each battle must receive at least the minimum required number of ships
    def battle_requirement_rule(model, j):
        return sum(model.x[i, j] for i in model.Ships) >= model.min_ships[j]
    model.battle_requirement_constraint = pyo.Constraint(model.Battles, rule=battle_requirement_rule)
    
    # The total number of ships assigned cannot exceed the maximum number available
    def max_ships_rule(model):
        return sum(model.x[i, j] for i in model.Ships for j in model.Battles) <= max_ships
    model.max_ships_constraint = pyo.Constraint(rule=max_ships_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
    # 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("\nAssignment values:")
        for i in model.Ships:
            for j in model.Battles:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0.5:  # Only print assignments
                    print(f"Ship {i} assigned to Battle {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
naval_optimization()