#!/usr/bin/env python3
"""
DOCPLEX implementation for school finance optimization problem
"""

from docplex.mp.model import Model

def school_finance_optimization():
    """Optimize budget allocation across schools to maximize educational impact."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="school_finance")
    
    # Data from the problem
    weights = [0.6, 0.8, 0.5]  # Educational impact per dollar
    min_investments = [60000, 70000, 50000]  # Minimum required investments
    total_budget = 1000000  # Total available budget
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(weights) == len(min_investments), "Array length mismatch"
    safe_range = range(min(len(weights), len(min_investments)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables: amount invested in each school
    x = {i: mdl.continuous_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total educational impact
    objective = mdl.sum(weights[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Total budget constraint
    total_investment = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_investment <= total_budget, ctname="total_budget")
    
    # Minimum investment constraints
    for i in safe_range:
        mdl.add_constraint(x[i] >= min_investments[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(x[i])
            print(f"Investment in School {i+1}: ${value:.2f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization
if __name__ == "__main__":
    school_finance_optimization()