# Complete DOCPLEX implementation - Retry Attempt 4

from docplex.mp.model import Model

def ship_mission_optimization():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="ship_mission")
    
    # Data from the problem statement
    ships = [
        {"Ship_ID": 1, "Tonnage": 1500.0, "cost_per_knot": 11.0, "cost_per_ton": 5.5},
        {"Ship_ID": 2, "Tonnage": 2500.0, "cost_per_knot": 13.0, "cost_per_ton": 6.0},
        {"Ship_ID": 3, "Tonnage": 1800.0, "cost_per_knot": 12.0, "cost_per_ton": 5.8}
    ]
    
    missions = [101, 102, 103]  # Assuming 3 missions for simplicity
    
    # Validate array lengths
    assert len(ships) == len(missions), "Mismatch between number of ships and missions"
    safe_range = range(len(ships))  # Safe indexing
    
    # 2. VARIABLES
    # Binary decision variables for ship-mission assignments
    x = {(i, j): mdl.binary_var(name=f"x_{i}_{j}") for i in safe_range for j in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize total operational cost
    objective = mdl.sum(
        (ships[i]["cost_per_knot"] + ships[i]["Tonnage"] * ships[i]["cost_per_ton"]) * x[i, j]
        for i in safe_range for j in safe_range
    )
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    # Each mission must be covered by exactly one ship
    for j in safe_range:
        mdl.add_constraint(mdl.sum(x[i, j] for i in safe_range) == 1, ctname=f"mission_coverage_{j}")
    
    # Each ship can be assigned to at most one mission
    for i in safe_range:
        mdl.add_constraint(mdl.sum(x[i, j] for j in safe_range) <= 1, ctname=f"ship_assignment_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            for j in safe_range:
                if solution.get_value(x[i, j]) > 0.5:  # Binary variable threshold
                    print(f"Ship {ships[i]['Ship_ID']} assigned to Mission {missions[j]}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

    return mdl

# Run the optimization
ship_mission_optimization()