## 4. Mathematical Optimization Formulation

#### Decision Variables
- Let \( x_{ij} \) be a binary decision variable where \( x_{ij} = 1 \) if complaint \( i \) is assigned to staff member \( j \), and \( x_{ij} = 0 \) otherwise.

#### Objective Function
Minimize the total resolution time for all complaints:
\[ \text{Minimize} \quad \sum_{i} \sum_{j} \text{resolution\_time}_i \times x_{ij} \]

Where:
- \(\text{resolution\_time}_i\) is the resolution time for complaint \( i \) from the `Complaints` table.

#### Constraints
1. Each complaint must be assigned to exactly one staff member:
   \[ \sum_{j} x_{ij} = 1 \quad \forall i \]

2. The number of complaints assigned to each staff member must not exceed their maximum handling capacity:
   \[ \sum_{i} x_{ij} \leq \text{max\_complaints}_j \quad \forall j \]

Where:
- \(\text{max\_complaints}_j\) is the maximum number of complaints staff member \( j \) can handle from the `StaffCapacity` table.

3. Binary constraint for decision variables:
   \[ x_{ij} \in \{0, 1\} \quad \forall i, j \]

Data Source Verification:
- \(\text{resolution\_time}_i\) is sourced from `Complaints.resolution_time`.
- \(\text{max\_complaints}_j\) is sourced from `StaffCapacity.max_complaints`. 

This linear model is designed to be immediately solvable using linear programming or mixed-integer programming techniques, ensuring that all constraints and the objective function are expressed in linear terms.

## 5. Gurobipy Implementation

```python
# Complete GUROBIPY implementation

import gurobipy as gp
from gurobipy import GRB

def optimize_customer_complaints():
    """Optimize the allocation of staff to manage customer complaints."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("customer_complaints")
    
    # Data from the database
    complaints = [
        {"complaint_id": 1, "resolution_time": 2},
        {"complaint_id": 2, "resolution_time": 3},
        {"complaint_id": 3, "resolution_time": 3}
    ]
    
    staff_capacity = [
        {"staff_id": 1, "max_complaints": 5},
        {"staff_id": 2, "max_complaints": 7},
        {"staff_id": 3, "max_complaints": 6}
    ]
    
    num_complaints = len(complaints)
    num_staff = len(staff_capacity)
    
    # CRITICAL: Validate array lengths before loops
    assert num_complaints > 0 and num_staff > 0, "No data available for complaints or staff"
    
    # 2. VARIABLES
    # Binary decision variables for complaint assignment
    x = model.addVars(num_complaints, num_staff, vtype=GRB.BINARY, name="x")
    
    # 3. OBJECTIVE FUNCTION
    # Minimize total resolution time
    model.setObjective(
        gp.quicksum(complaints[i]["resolution_time"] * x[i, j] for i in range(num_complaints) for j in range(num_staff)),
        GRB.MINIMIZE
    )
    
    # 4. CONSTRAINTS
    
    # Each complaint must be assigned to exactly one staff member
    model.addConstrs(
        (gp.quicksum(x[i, j] for j in range(num_staff)) == 1 for i in range(num_complaints)),
        name="assign_complaint"
    )
    
    # The number of complaints assigned to each staff member must not exceed their capacity
    model.addConstrs(
        (gp.quicksum(x[i, j] for i in range(num_complaints)) <= staff_capacity[j]["max_complaints"] for j in range(num_staff)),
        name="staff_capacity"
    )
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(num_complaints):
            for j in range(num_staff):
                if x[i, j].x > 1e-6:
                    print(f"Complaint {complaints[i]['complaint_id']} assigned to Staff {staff_capacity[j]['staff_id']}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Run the optimization
optimize_customer_complaints()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 8.0
**Execution Time**: 1.06 seconds
**Reliability**: high
**Analysis**: Gurobipy successfully found an optimal solution with the lowest execution time among the solvers, indicating efficient performance.

## 6. DOCplex Implementation

```python
# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_customer_complaints():
    """Optimize the allocation of staff to manage customer complaints."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="customer_complaints")
    
    # Data from the database
    resolution_times = [2, 3, 3]  # From Complaints table
    max_complaints = [5, 7, 6]    # From StaffCapacity table
    
    n_complaints = len(resolution_times)
    n_staff = len(max_complaints)
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(resolution_times) == n_complaints, "Resolution times length mismatch"
    assert len(max_complaints) == n_staff, "Max complaints length mismatch"
    
    # Safe range for indexing
    safe_complaints_range = range(n_complaints)
    safe_staff_range = range(n_staff)
    
    # 2. VARIABLES
    # Binary decision variables: x[i][j] = 1 if complaint i is assigned to staff j
    x = {(i, j): mdl.binary_var(name=f"x_{i}_{j}") for i in safe_complaints_range for j in safe_staff_range}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total resolution time
    objective = mdl.sum(resolution_times[i] * x[i, j] for i in safe_complaints_range for j in safe_staff_range)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    
    # Each complaint must be assigned to exactly one staff member
    for i in safe_complaints_range:
        mdl.add_constraint(mdl.sum(x[i, j] for j in safe_staff_range) == 1, ctname=f"assign_complaint_{i}")
    
    # The number of complaints assigned to each staff member must not exceed their capacity
    for j in safe_staff_range:
        mdl.add_constraint(mdl.sum(x[i, j] for i in safe_complaints_range) <= max_complaints[j], ctname=f"staff_capacity_{j}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_complaints_range:
            for j in safe_staff_range:
                if solution.get_value(x[i, j]) > 1e-6:
                    print(f"Complaint {i} assigned to Staff {j}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

    return mdl

# Run the optimization
optimize_customer_complaints()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 8.0
**Execution Time**: 1.11 seconds
**Reliability**: high
**Analysis**: DOCplex also found an optimal solution with a slightly higher execution time than Gurobipy, but still within an acceptable range.

## 7. Pyomo Implementation

```python
# 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()
```

### Execution Results
**Status**: OPTIMAL
**Optimal Value**: 8.0
**Execution Time**: 1.93 seconds
**Reliability**: high
**Analysis**: Pyomo achieved an optimal solution, albeit with the highest execution time. This suggests it is less efficient but still reliable.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | OPTIMAL | 8.00 | 1.06s | N/A | N/A |
| Docplex | OPTIMAL | 8.00 | 1.11s | N/A | N/A |
| Pyomo | OPTIMAL | 8.00 | 1.93s | N/A | N/A |

### Solver Consistency Analysis
**Result**: All solvers produced consistent results ✓
**Consistent Solvers**: gurobipy, docplex, pyomo
**Majority Vote Optimal Value**: 8.0

### Final Recommendation
**Recommended Optimal Value**: 8.0
**Confidence Level**: HIGH
**Preferred Solver(s)**: gurobipy
**Reasoning**: Gurobipy is recommended due to its optimal solution and the fastest execution time, making it the most efficient choice for this problem.

### Business Interpretation
**Overall Strategy**: The optimal resolution time of 8.0 indicates efficient allocation of complaints to staff, minimizing total resolution time.
**Objective Value Meaning**: The optimal objective value of 8.0 represents the minimized total resolution time for all complaints, indicating efficient resource allocation.
**Resource Allocation Summary**: Each complaint is assigned to a staff member in a way that minimizes total resolution time while respecting capacity constraints.
**Implementation Recommendations**: Implement the solution by assigning complaints to staff as per the decision variables, ensuring adherence to capacity constraints and monitoring resolution times for continuous improvement.