# Complete PYOMO implementation - Retry Attempt 1

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

def department_budget_optimization():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    departments = [1, 2, 3]
    rankings = {1: 10, 2: 8, 3: 6}  # Example rankings
    employees = {1: 50, 2: 40, 3: 30}  # Example number of employees
    min_budgets = {1: 100000, 2: 80000, 3: 50000}
    max_budgets = {1: 300000, 2: 250000, 3: 200000}
    total_budget = 1000000
    
    # Validate array lengths
    assert len(departments) == len(rankings) == len(employees) == len(min_budgets) == len(max_budgets), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=departments)
    
    # 4. PARAMETERS
    model.ranking = pyo.Param(model.I, initialize=rankings)
    model.employees = pyo.Param(model.I, initialize=employees)
    model.min_budget = pyo.Param(model.I, initialize=min_budgets)
    model.max_budget = pyo.Param(model.I, initialize=max_budgets)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum((0.7 * model.ranking[i] + 0.3 * model.employees[i]) * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    def total_budget_rule(model):
        return sum(model.x[i] for i in model.I) <= total_budget
    model.total_budget_constraint = pyo.Constraint(rule=total_budget_rule)
    
    def min_budget_rule(model, i):
        return model.x[i] >= model.min_budget[i]
    model.min_budget_constraint = pyo.Constraint(model.I, rule=min_budget_rule)
    
    def max_budget_rule(model, i):
        return model.x[i] <= model.max_budget[i]
    model.max_budget_constraint = pyo.Constraint(model.I, rule=max_budget_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    results = solver.solve(model, tee=True)
    
    # 9. RESULT PROCESSING
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nAllocated Budgets:")
        for i in model.I:
            print(f"Department {i}: {pyo.value(model.x[i]):.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

if __name__ == "__main__":
    department_budget_optimization()