# Complete PYOMO implementation

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

def school_finance_optimization():
    """Optimize school budget allocation to maximize educational impact."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    schools = [1, 2, 3]
    weights = {1: 0.6, 2: 0.8, 3: 0.5}
    min_investments = {1: 60000, 2: 70000, 3: 50000}
    total_budget = 1000000
    
    # CRITICAL: Validate array lengths before indexing
    assert len(weights) == len(min_investments) == len(schools), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=schools)
    
    # 4. PARAMETERS (data containers)
    model.weight = pyo.Param(model.I, initialize=weights)
    model.min_investment = pyo.Param(model.I, initialize=min_investments)
    model.total_budget = pyo.Param(initialize=total_budget)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.weight[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total Budget Constraint
    def budget_rule(model):
        return sum(model.x[i] for i in model.I) <= model.total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_rule)
    
    # Minimum Investment Constraints
    def min_investment_rule(model, i):
        return model.x[i] >= model.min_investment[i]
    model.min_investment_constraint = pyo.Constraint(model.I, rule=min_investment_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 amounts:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            print(f"School {i}: ${x_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

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