# Complete PYOMO implementation - Retry Attempt 4

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

def employee_hire_evaluation():
    """Optimize employee assignments to maximize bonuses."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Employee and shop data
    employees = [1, 2, 3]
    shops = [101, 102, 103]
    bonuses = {1: 500.0, 2: 750.0, 3: 1000.0}
    min_employees = {101: 3, 102: 4, 103: 5}
    
    # CRITICAL: Validate data lengths
    assert len(bonuses) == len(employees), "Mismatch in bonuses and employees"
    assert len(min_employees) == len(shops), "Mismatch in min_employees and shops"
    
    # 3. SETS
    model.I = pyo.Set(initialize=employees)
    model.J = pyo.Set(initialize=shops)
    
    # 4. PARAMETERS
    model.bonus = pyo.Param(model.I, initialize=bonuses)
    model.min_employees = pyo.Param(model.J, initialize=min_employees)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.bonus[i] * model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Each employee is assigned to exactly one shop
    def employee_assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.J) == 1
    model.employee_assignment = pyo.Constraint(model.I, rule=employee_assignment_rule)
    
    # Each shop meets its minimum staffing requirement
    def shop_staffing_rule(model, j):
        return sum(model.x[i, j] for i in model.I) >= model.min_employees[j]
    model.shop_staffing = pyo.Constraint(model.J, rule=shop_staffing_rule)
    
    # 8. SOLVING WITH GUROBI
    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)
    
    # 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("\nEmployee assignments:")
        for i in model.I:
            for j in model.J:
                if pyo.value(model.x[i, j]) > 0.5:  # Binary variable, check if assigned
                    print(f"Employee {i} assigned to Shop {j}")
        
    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
employee_hire_evaluation()