# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_editor_journal_assignment():
    """Optimize the assignment of editors to journals to maximize sales."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="journal_committee")
    
    # Data from the problem context
    editors = [1, 2, 3]
    journals = [101, 102, 103]
    sales = {101: 1200.0, 102: 1800.0, 103: 1600.0}
    qualifications = {
        1: ['Science'],
        2: ['Arts'],
        3: ['Technology']
    }
    journal_themes = {
        101: 'Science',
        102: 'Arts',
        103: 'Technology'
    }
    max_journals_per_editor = {1: 2, 2: 2, 3: 2}  # Example workload limits
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(editors) == len(max_journals_per_editor), "Array length mismatch"
    safe_range_editors = range(len(editors))
    safe_range_journals = range(len(journals))
    
    # 2. VARIABLES
    # Binary decision variables for editor-journal assignments
    x = {(i, j): mdl.binary_var(name=f"x_{i}_{j}") for i in editors for j in journals}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total sales from journal assignments
    objective = mdl.sum(sales[j] * x[i, j] for i in editors for j in journals)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Editor Workload Constraint
    for i in editors:
        mdl.add_constraint(mdl.sum(x[i, j] for j in journals) <= max_journals_per_editor[i], ctname=f"workload_{i}")
    
    # Qualification Constraint
    for i in editors:
        for j in journals:
            if journal_themes[j] not in qualifications[i]:
                mdl.add_constraint(x[i, j] == 0, ctname=f"qualification_{i}_{j}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in editors:
            for j in journals:
                value = solution.get_value(x[i, j])
                if value > 1e-6:
                    print(f"x[{i},{j}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_editor_journal_assignment()