# Complete PYOMO implementation - Retry Attempt 4

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

def optimize_battle_death():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    ships = [1, 2, 3]
    battles = [1, 2, 3]
    
    # Ship tonnage data
    ship_tonnage_data = {
        1: 5000,
        2: 7000,
        3: 9000
    }
    
    # Battle constraints data
    battle_constraints_data = {
        1: 10000,
        2: 12000,
        3: 15000
    }
    
    # Casualties data
    casualties_data = {
        (1, 1): (10, 15),
        (2, 2): (20, 25),
        (3, 3): (30, 35)
    }
    
    # Validate array lengths
    assert len(ship_tonnage_data) == len(ships), "Ship tonnage data length mismatch"
    assert len(battle_constraints_data) == len(battles), "Battle constraints data length mismatch"
    assert len(casualties_data) == len(ships) * len(battles), "Casualties data length mismatch"
    
    # 3. SETS
    model.S = pyo.Set(initialize=ships)
    model.B = pyo.Set(initialize=battles)
    
    # 4. PARAMETERS
    model.tonnage = pyo.Param(model.S, initialize=ship_tonnage_data)
    model.max_tonnage = pyo.Param(model.B, initialize=battle_constraints_data)
    model.killed = pyo.Param(model.S, model.B, initialize=lambda model, s, b: casualties_data[(s, b)][0])
    model.injured = pyo.Param(model.S, model.B, initialize=lambda model, s, b: casualties_data[(s, b)][1])
    
    # 5. VARIABLES
    model.x = pyo.Var(model.S, model.B, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum((model.killed[s, b] + model.injured[s, b]) * model.x[s, b] for s in model.S for b in model.B)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Tonnage Constraint
    def tonnage_rule(model, b):
        return sum(model.tonnage[s] * model.x[s, b] for s in model.S) <= model.max_tonnage[b]
    model.tonnage_constraint = pyo.Constraint(model.B, rule=tonnage_rule)
    
    # Single Deployment Constraint
    def deployment_rule(model, s):
        return sum(model.x[s, b] for b in model.B) <= 1
    model.deployment_constraint = pyo.Constraint(model.S, rule=deployment_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("\nDeployment decisions:")
        for s in model.S:
            for b in model.B:
                if pyo.value(model.x[s, b]) > 0.5:  # Only print deployed ships
                    print(f"Ship {s} deployed to Battle {b}")
        
    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
if __name__ == "__main__":
    optimize_battle_death()