# Complete PYOMO implementation

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

def optimize_customer_complaints():
    """Optimize the allocation of staff to manage customer complaints"""

    # 1. MODEL CREATION
    model = pyo.ConcreteModel()

    # 2. DATA SETUP
    # Example data based on the provided database schema and stored values
    complaints = [1, 2, 3]
    staff_members = [1, 2, 3]
    resolution_times = {1: 2, 2: 3, 3: 3}
    max_complaints = {1: 5, 2: 7, 3: 6}

    # CRITICAL: Validate array lengths before indexing
    assert len(complaints) == len(resolution_times), "Array length mismatch for complaints and resolution times"
    assert len(staff_members) == len(max_complaints), "Array length mismatch for staff members and max complaints"

    # 3. SETS
    model.I = pyo.Set(initialize=complaints)
    model.J = pyo.Set(initialize=staff_members)

    # 4. PARAMETERS
    model.resolution_time = pyo.Param(model.I, initialize=resolution_times)
    model.max_complaints = pyo.Param(model.J, initialize=max_complaints)

    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.Binary)

    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.resolution_time[i] * model.x[i, j] for i in model.I for j in model.J)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)

    # 7. CONSTRAINTS
    # Each complaint must be assigned to exactly one staff member
    def assignment_rule(model, i):
        return sum(model.x[i, j] for j in model.J) == 1
    model.assignment_constraint = pyo.Constraint(model.I, rule=assignment_rule)

    # The number of complaints assigned to each staff member must not exceed their maximum handling capacity
    def capacity_rule(model, j):
        return sum(model.x[i, j] for i in model.I) <= model.max_complaints[j]
    model.capacity_constraint = pyo.Constraint(model.J, rule=capacity_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("\nAssignment of complaints to staff members:")
        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"Complaint {i} assigned to Staff {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
optimize_customer_complaints()