# Complete DOCPLEX implementation

from docplex.mp.model import Model

def department_management_optimization():
    """Optimization for department budget allocation"""

    # 1. MODEL & DATA SETUP
    mdl = Model(name="department_management")
    
    # Data from the problem context
    rankings = [1.8, 2.5, 3.2]
    budgets_in_billions = [0.6, 1.2, 1.8]
    total_budget = 3  # Total budget in billions
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(rankings) == len(budgets_in_billions) == 3, "Array length mismatch"
    safe_range = range(min(len(rankings), len(budgets_in_billions)))  # Safe indexing
    
    # 2. VARIABLES
    # Variable dictionaries (most common)
    fraction_allocated = {i: mdl.continuous_var(name=f"x_{i}", lb=0, ub=1) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Use mdl.sum() for summations (DOCplex specific)
    objective = mdl.sum(rankings[i] * fraction_allocated[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total budget allocation constraint
    total_allocation = mdl.sum(fraction_allocated[i] * budgets_in_billions[i] for i in safe_range)
    mdl.add_constraint(total_allocation <= total_budget, ctname="total_budget_constraint")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(fraction_allocated[i])
            print(f"Fraction allocated to department {i+1}: {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
department_management_optimization()