# Complete DOCPLEX implementation - Retry Attempt 1

from docplex.mp.model import Model

def department_budget_optimization():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="department_budget_optimization")
    
    # Data from the problem
    departments = [1, 2, 3]
    minimum_budgets = [100000, 80000, 50000]
    maximum_budgets = [300000, 250000, 200000]
    rankings = [10, 8, 6]  # Example rankings (higher is better)
    employees = [50, 40, 30]  # Example number of employees
    total_budget = 1000000
    
    # Efficiency weights
    ranking_weight = 0.7
    employees_weight = 0.3
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(departments) == len(minimum_budgets) == len(maximum_budgets) == len(rankings) == len(employees), "Array length mismatch"
    safe_range = range(min(len(departments), len(minimum_budgets), len(maximum_budgets), len(rankings), len(employees)))  # Safe indexing
    
    # 2. VARIABLES
    x = {i: mdl.continuous_var(name=f"x_{i}", lb=minimum_budgets[i], ub=maximum_budgets[i]) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Calculate efficiency coefficients
    c = {i: ranking_weight * rankings[i] + employees_weight * employees[i] for i in safe_range}
    
    # Maximize the overall efficiency score
    objective = mdl.sum(c[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    # Total Budget Constraint
    total_budget_constraint = mdl.sum(x[i] for i in safe_range) <= total_budget
    mdl.add_constraint(total_budget_constraint, ctname="total_budget")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(x[i])
            print(f"x[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization
department_budget_optimization()