# Complete DOCPLEX implementation

from docplex.mp.model import Model

def school_finance_optimization():
    """Optimize school budget allocation using DOCPLEX"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="school_finance")
    
    # Data from the database
    budgeted = [5000.0, 6000.0, 7000.0]
    min_investment_percent = [0.1, 0.15, 0.2]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(budgeted) == len(min_investment_percent), "Array length mismatch"
    safe_range = range(len(budgeted))  # Safe indexing
    
    # 2. VARIABLES
    invested = {i: mdl.continuous_var(name=f"Invested_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total amount invested across all schools
    objective = mdl.sum(invested[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Investment should not exceed the budgeted amount for each school
    for i in safe_range:
        mdl.add_constraint(invested[i] <= budgeted[i], ctname=f"budget_limit_{i}")
    
    # Investment should be at least the minimum percentage of the budgeted amount
    for i in safe_range:
        mdl.add_constraint(invested[i] >= min_investment_percent[i] * budgeted[i], ctname=f"min_investment_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(invested[i])
            if value > 1e-6:
                print(f"Invested[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
school_finance_optimization()