# Complete GUROBIPY implementation - Retry Attempt 4

import gurobipy as gp
from gurobipy import GRB

def optimize_ship_captain_assignment():
    # 1. MODEL & DATA SETUP
    model = gp.Model("ship_captain_assignment")
    
    # Data from the database
    captains = [1, 2, 3]
    ships = [1, 2, 3]
    
    cost_coefficients = {
        (1, 1): 1200,
        (2, 2): 1500,
        (3, 3): 1000
    }
    
    compatibility_rules = {
        (1, 1): True,
        (2, 2): True,
        (3, 3): False
    }
    
    age_rules = {
        (1, 1): True,
        (2, 2): True,
        (3, 3): False
    }
    
    # CRITICAL: Validate array lengths before loops
    assert len(captains) == len(ships), "Array length mismatch"
    
    # 2. VARIABLES
    x = model.addVars(captains, ships, vtype=GRB.BINARY, name="x")
    
    # 3. OBJECTIVE FUNCTION
    model.setObjective(gp.quicksum(cost_coefficients[(i, j)] * x[i, j] for i in captains for j in ships), GRB.MINIMIZE)
    
    # 4. CONSTRAINTS
    
    # Ship Assignment Constraint: Each ship must be assigned exactly one captain
    for j in ships:
        model.addConstr(gp.quicksum(x[i, j] for i in captains) == 1, name=f"ship_assignment_{j}")
    
    # Captain Assignment Constraint: Each captain can be assigned to at most one ship
    for i in captains:
        model.addConstr(gp.quicksum(x[i, j] for j in ships) <= 1, name=f"captain_assignment_{i}")
    
    # Compatibility Constraint: A captain can only be assigned to a ship if their rank is compatible with the ship's type
    for i in captains:
        for j in ships:
            model.addConstr(x[i, j] <= compatibility_rules[(i, j)], name=f"compatibility_{i}_{j}")
    
    # Age Constraint: A captain can only be assigned to a ship if the ship's age is acceptable for their rank
    for i in captains:
        for j in ships:
            model.addConstr(x[i, j] <= age_rules[(i, j)], name=f"age_{i}_{j}")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in captains:
            for j in ships:
                if x[i, j].x > 1e-6:
                    print(f"Captain {i} assigned to Ship {j}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Execute the optimization
optimize_ship_captain_assignment()