# Complete GUROBIPY implementation

import gurobipy as gp
from gurobipy import GRB

def optimize_school_finance():
    """Optimize school budget allocation using Gurobi"""

    # 1. MODEL & DATA SETUP
    model = gp.Model("school_finance")

    # Data from the database
    budget_data = [
        {"Invested": 4500.0, "Budgeted": 5000.0, "min_investment_percent": 0.1},
        {"Invested": 5400.0, "Budgeted": 6000.0, "min_investment_percent": 0.15},
        {"Invested": 6300.0, "Budgeted": 7000.0, "min_investment_percent": 0.2}
    ]

    n_schools = len(budget_data)

    # Extracting data into lists
    budgeted = [entry["Budgeted"] for entry in budget_data]
    min_investment_percent = [entry["min_investment_percent"] for entry in budget_data]

    # CRITICAL: Validate array lengths before loops
    assert len(budgeted) == len(min_investment_percent) == n_schools, "Array length mismatch"

    # 2. VARIABLES
    invested = model.addVars(n_schools, vtype=GRB.CONTINUOUS, name="Invested", lb=0)

    # 3. OBJECTIVE FUNCTION
    model.setObjective(gp.quicksum(invested[i] for i in range(n_schools)), GRB.MAXIMIZE)

    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS

    # Constraint: Investment should not exceed the budgeted amount for each school
    model.addConstrs((invested[i] <= budgeted[i] for i in range(n_schools)), name="budget_limit")

    # Constraint: Investment should be at least the minimum percentage of the budgeted amount
    model.addConstrs((invested[i] >= min_investment_percent[i] * budgeted[i] for i in range(n_schools)), name="min_investment")

    # 5. SOLVING & RESULTS
    model.optimize()

    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_schools):
            if invested[i].x > 1e-6:
                print(f"Invested[{i}] = {invested[i].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")

    return model

# Run the optimization
optimize_school_finance()