# Complete PYOMO implementation

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

def department_management_optimization():
    """Optimization for department budget allocation"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    n_departments = 3
    rankings = [1.8, 2.5, 3.2]
    budgets = [0.6, 1.2, 1.8]
    total_budget = 3.0  # Total budget in billions
    
    # CRITICAL: Validate array lengths before indexing
    assert len(rankings) == len(budgets) == n_departments, "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.RangeSet(1, n_departments)  # 1-based indexing
    
    # 4. PARAMETERS (data containers)
    model.ranking = pyo.Param(model.I, initialize={i+1: rankings[i] for i in range(n_departments)})
    model.budget = pyo.Param(model.I, initialize={i+1: budgets[i] for i in range(n_departments)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals, bounds=(0, 1))
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.ranking[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total budget allocation constraint
    def budget_constraint_rule(model):
        return sum(model.x[i] * model.budget[i] for i in model.I) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_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):.3f}")
        
        # Extract variable values
        print("\nVariable values:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {x_val:.3f}")
        
    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
department_management_optimization()