# Complete PYOMO implementation

import pyomo.environ as pyo
from pyomo.opt import SolverFactory

def school_finance_optimization():
    """Optimize school budget allocation using Pyomo"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data from the database
    budgeted = [5000.0, 6000.0, 7000.0]
    min_investment_percent = [0.1, 0.15, 0.2]
    
    # CRITICAL: Validate array lengths before indexing
    n_schools = len(budgeted)
    assert len(min_investment_percent) == n_schools, "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.S = pyo.RangeSet(1, n_schools)  # 1-based indexing
    
    # 4. PARAMETERS (data containers)
    model.Budgeted = pyo.Param(model.S, initialize={i+1: budgeted[i] for i in range(n_schools)})
    model.MinInvestmentPercent = pyo.Param(model.S, initialize={i+1: min_investment_percent[i] for i in range(n_schools)})
    
    # 5. VARIABLES
    model.Invested = pyo.Var(model.S, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.Invested[i] for i in model.S)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Constraint: Investment should not exceed the budgeted amount for each school
    def budget_constraint_rule(model, i):
        return model.Invested[i] <= model.Budgeted[i]
    model.budget_constraint = pyo.Constraint(model.S, rule=budget_constraint_rule)
    
    # Constraint: Investment should be at least the minimum percentage of the budgeted amount
    def min_investment_constraint_rule(model, i):
        return model.Invested[i] >= model.MinInvestmentPercent[i] * model.Budgeted[i]
    model.min_investment_constraint = pyo.Constraint(model.S, rule=min_investment_constraint_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    solver = SolverFactory('gurobi')
    
    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap
    
    # Solve the model
    results = solver.solve(model, tee=True)  # tee=True shows solver output
    
    # 9. RESULT PROCESSING
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nInvestment values:")
        for i in model.S:
            invested_val = pyo.value(model.Invested[i])
            print(f"Invested[{i}] = {invested_val:.2f}")
        
    elif results.solver.termination_condition == pyo.TerminationCondition.infeasible:
        print("Problem is infeasible")
    elif results.solver.termination_condition == pyo.TerminationCondition.unbounded:
        print("Problem is unbounded")
    else:
        print(f"Solver terminated with condition: {results.solver.termination_condition}")
    
    return model

# Run the optimization
school_finance_optimization()