# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_captain_assignment():
    """Optimize the assignment of captains to ships to minimize total age."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="captain_assignment")
    
    # Data: Captains and their ages
    captains = [1, 2, 3]
    ages = [45, 50, 55]
    ships = [101, 102, 103]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(captains) == len(ages), "Array length mismatch for captains and ages"
    assert len(captains) == len(ships), "Array length mismatch for captains and ships"
    safe_range = range(len(captains))  # Safe indexing
    
    # 2. VARIABLES
    # Binary decision variables for captain-ship 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 the total age of captains assigned to ships
    objective = mdl.sum(ages[i] * x[i, j] for i in safe_range for j in safe_range)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Each captain is assigned to exactly one ship
    for i in safe_range:
        mdl.add_constraint(mdl.sum(x[i, j] for j in safe_range) == 1, ctname=f"captain_{i}_assignment")
    
    # Each ship has exactly one captain
    for j in safe_range:
        mdl.add_constraint(mdl.sum(x[i, j] for i in safe_range) == 1, ctname=f"ship_{j}_assignment")
    
    # Only eligible captains (age ≤ 60) can be assigned
    for i in safe_range:
        if ages[i] > 60:
            for j in safe_range:
                mdl.add_constraint(x[i, j] == 0, ctname=f"eligibility_{i}_{j}")
    
    # 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:
                value = solution.get_value(x[i, j])
                if value > 1e-6:
                    print(f"Captain {captains[i]} assigned to Ship {ships[j]}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_captain_assignment()