## 4. Mathematical Optimization Formulation

#### Decision Variables
- \( x_{i,j} \): Time spent by staff member \( i \) on complaint \( j \).  
  - **Type**: Continuous  
  - **Domain**: \( x_{i,j} \geq 0 \)  

#### Objective Function
Minimize the total cost of handling complaints:  
\[
\text{Minimize } Z = \sum_{i} \sum_{j} (\text{hourly\_wage}_i \times x_{i,j})
\]  
- **Coefficient Source**: `staff_wages.hourly_wage`  

#### Constraints
1. **Complaint Assignment Constraint**: Each complaint must be fully assigned to one or more staff members:  
\[
\sum_{i} x_{i,j} = 1 \quad \forall j
\]  
- **Coefficient Source**: Each complaint must sum to exactly 1 unit of time.  

2. **Time Bounds Constraint**: The time spent by any staff member on a specific complaint must fall within the predefined minimum and maximum time limits for that complaint:  
\[
\text{min\_time}_j \leq x_{i,j} \leq \text{max\_time}_j \quad \forall i, j
\]  
- **Coefficient Source**: `complaint_time_constraints.min_time` and `complaint_time_constraints.max_time`  

3. **Staff Working Hours Constraint**: The total time spent by each staff member across all complaints must not exceed their maximum working hours:  
\[
\sum_{j} x_{i,j} \leq \text{max\_hours}_i \quad \forall i
\]  
- **Coefficient Source**: `staff_working_hours.max_hours`  

#### Data Source Verification
- **Objective Function Coefficients**: `staff_wages.hourly_wage`  
- **Complaint Assignment Constraint**: Each complaint must sum to exactly 1 unit of time.  
- **Time Bounds Constraint**: `complaint_time_constraints.min_time` and `complaint_time_constraints.max_time`  
- **Staff Working Hours Constraint**: `staff_working_hours.max_hours`  

This formulation provides a complete, immediately solvable LINEAR mathematical model with all numerical coefficients derived from the provided data.

## 5. Gurobipy Implementation

```python
# Complete GUROBIPY implementation - Retry Attempt 4

import gurobipy as gp
from gurobipy import GRB

def optimize_customer_complaints():
    # 1. MODEL & DATA SETUP
    model = gp.Model("customer_complaints")
    
    # Data from the database
    staff_wages = {1: 25.0, 2: 30.0, 3: 35.0}
    complaint_time_constraints = {
        1: {'min_time': 1.0, 'max_time': 3.0},
        2: {'min_time': 1.5, 'max_time': 4.0},
        3: {'min_time': 2.0, 'max_time': 5.0}
    }
    staff_working_hours = {1: 40.0, 2: 45.0, 3: 50.0}
    
    # Extract staff and complaint IDs
    staff_ids = list(staff_wages.keys())
    complaint_ids = list(complaint_time_constraints.keys())
    
    # CRITICAL: Validate array lengths before loops
    assert len(staff_ids) > 0, "No staff members found"
    assert len(complaint_ids) > 0, "No complaints found"
    
    # 2. VARIABLES
    # Decision variable: time spent by staff member i on complaint j
    x = model.addVars(staff_ids, complaint_ids, vtype=GRB.CONTINUOUS, name="x", lb=0)
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total cost of handling complaints
    model.setObjective(
        gp.quicksum(staff_wages[i] * x[i, j] for i in staff_ids for j in complaint_ids),
        GRB.MINIMIZE
    )
    
    # 4. CONSTRAINTS
    
    # Complaint Assignment Constraint: Each complaint must be fully assigned
    for j in complaint_ids:
        model.addConstr(
            gp.quicksum(x[i, j] for i in staff_ids) == 1,
            name=f"complaint_assignment_{j}"
        )
    
    # Time Bounds Constraint: Time spent must be within min and max time for each complaint
    for i in staff_ids:
        for j in complaint_ids:
            model.addConstr(
                x[i, j] >= complaint_time_constraints[j]['min_time'],
                name=f"min_time_{i}_{j}"
            )
            model.addConstr(
                x[i, j] <= complaint_time_constraints[j]['max_time'],
                name=f"max_time_{i}_{j}"
            )
    
    # Staff Working Hours Constraint: Total time spent by each staff member must not exceed max hours
    for i in staff_ids:
        model.addConstr(
            gp.quicksum(x[i, j] for j in complaint_ids) <= staff_working_hours[i],
            name=f"staff_hours_{i}"
        )
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in staff_ids:
            for j in complaint_ids:
                if x[i, j].x > 1e-6:
                    print(f"x[{i},{j}] = {x[i, j].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Execute the optimization
optimize_customer_complaints()
```

### Execution Results
**Status**: INFEASIBLE
**Error**: Problem is infeasible
**Analysis**: Gurobipy identified the problem as infeasible, indicating that the constraints cannot be satisfied simultaneously. This is a reliable result given Gurobipy's robust algorithms.

## 6. DOCplex Implementation

```python
# Complete DOCPLEX implementation - Retry Attempt 4

from docplex.mp.model import Model

def optimize_customer_complaints():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="customer_complaints_optimization")
    
    # Data from the database
    staff_wages = [
        (1, 25.0),
        (2, 30.0),
        (3, 35.0)
    ]
    
    complaint_time_constraints = [
        (1, 1.0, 3.0),
        (2, 1.5, 4.0),
        (3, 2.0, 5.0)
    ]
    
    staff_working_hours = [
        (1, 40.0),
        (2, 45.0),
        (3, 50.0)
    ]
    
    # Extract unique staff and complaint IDs
    staff_ids = sorted({sw[0] for sw in staff_wages})
    complaint_ids = sorted({ctc[0] for ctc in complaint_time_constraints})
    
    # Create dictionaries for easy access
    hourly_wage = {sw[0]: sw[1] for sw in staff_wages}
    min_time = {ctc[0]: ctc[1] for ctc in complaint_time_constraints}
    max_time = {ctc[0]: ctc[2] for ctc in complaint_time_constraints}
    max_hours = {swh[0]: swh[1] for swh in staff_working_hours}
    
    # 2. VARIABLES
    # Decision variable: time spent by staff member i on complaint j
    x = {(i, j): mdl.continuous_var(name=f"x_{i}_{j}", lb=0) for i in staff_ids for j in complaint_ids}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total cost of handling complaints
    total_cost = mdl.sum(hourly_wage[i] * x[i, j] for i in staff_ids for j in complaint_ids)
    mdl.minimize(total_cost)
    
    # 4. CONSTRAINTS
    
    # Complaint Assignment Constraint: Each complaint must be fully assigned
    for j in complaint_ids:
        mdl.add_constraint(mdl.sum(x[i, j] for i in staff_ids) == 1, ctname=f"complaint_assignment_{j}")
    
    # Time Bounds Constraint: Time spent must be within min and max time for each complaint
    for i in staff_ids:
        for j in complaint_ids:
            mdl.add_constraint(x[i, j] >= min_time[j], ctname=f"min_time_{i}_{j}")
            mdl.add_constraint(x[i, j] <= max_time[j], ctname=f"max_time_{i}_{j}")
    
    # Staff Working Hours Constraint: Total time spent by each staff member must not exceed max hours
    for i in staff_ids:
        mdl.add_constraint(mdl.sum(x[i, j] for j in complaint_ids) <= max_hours[i], ctname=f"max_hours_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in staff_ids:
            for j in complaint_ids:
                value = solution.get_value(x[i, j])
                if value > 1e-6:
                    print(f"Time spent by staff {i} on complaint {j}: {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
        if mdl.solve_details.status == "infeasible":
            print("The problem is infeasible. Please check the constraints.")
        elif mdl.solve_details.status == "unbounded":
            print("The problem is unbounded. Please check the objective function.")
    
    return mdl

# Run the optimization
optimize_customer_complaints()
```

### Execution Results
**Status**: INFEASIBLE
**Error**: Problem is infeasible
**Analysis**: DOCplex also concluded that the problem is infeasible, aligning with Gurobipy's result. This consistency reinforces the reliability of the infeasibility diagnosis.

## 7. Pyomo Implementation

```python
# Complete PYOMO implementation - Retry Attempt 4

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

def customer_complaints_optimization():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Staff data
    staff_ids = [1, 2, 3]
    hourly_wages = {1: 25.0, 2: 30.0, 3: 35.0}
    max_hours = {1: 40.0, 2: 45.0, 3: 50.0}
    
    # Complaint data
    complaint_ids = [1, 2, 3]
    min_time = {1: 1.0, 2: 1.5, 3: 2.0}
    max_time = {1: 3.0, 2: 4.0, 3: 5.0}
    
    # Validate array lengths
    assert len(staff_ids) == len(hourly_wages) == len(max_hours), "Staff data length mismatch"
    assert len(complaint_ids) == len(min_time) == len(max_time), "Complaint data length mismatch"
    
    # 3. SETS
    model.staff = pyo.Set(initialize=staff_ids)
    model.complaints = pyo.Set(initialize=complaint_ids)
    
    # 4. PARAMETERS
    model.hourly_wage = pyo.Param(model.staff, initialize=hourly_wages)
    model.max_hours = pyo.Param(model.staff, initialize=max_hours)
    model.min_time = pyo.Param(model.complaints, initialize=min_time)
    model.max_time = pyo.Param(model.complaints, initialize=max_time)
    
    # 5. VARIABLES
    model.time_spent = pyo.Var(model.staff, model.complaints, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.hourly_wage[i] * model.time_spent[i, j] for i in model.staff for j in model.complaints)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Complaint Assignment Constraint
    def complaint_assignment_rule(model, j):
        return sum(model.time_spent[i, j] for i in model.staff) == 1
    model.complaint_assignment = pyo.Constraint(model.complaints, rule=complaint_assignment_rule)
    
    # Time Bounds Constraint
    def time_bounds_rule(model, i, j):
        return (model.min_time[j], model.time_spent[i, j], model.max_time[j])
    model.time_bounds = pyo.Constraint(model.staff, model.complaints, rule=time_bounds_rule)
    
    # Staff Working Hours Constraint
    def staff_hours_rule(model, i):
        return sum(model.time_spent[i, j] for j in model.complaints) <= model.max_hours[i]
    model.staff_hours = pyo.Constraint(model.staff, rule=staff_hours_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)  # 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)}")
        
        # Extract variable values
        print("\nTime spent by staff on complaints:")
        for i in model.staff:
            for j in model.complaints:
                time_val = pyo.value(model.time_spent[i, j])
                if time_val > 1e-6:  # Only print non-zero values
                    print(f"Staff {i} spent {time_val:.3f} hours on complaint {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

# Execute the optimization
if __name__ == "__main__":
    customer_complaints_optimization()
```

### Execution Results
**Status**: INFEASIBLE
**Error**: Problem is infeasible
**Analysis**: Pyomo also reported infeasibility, but its execution time was slightly longer. While the result is consistent with the other solvers, Pyomo's performance is less efficient.

## 8. Cross-Solver Analysis and Final Recommendation

### Solver Results Comparison

| Solver | Status | Optimal Value | Execution Time | Decision Variables | Retry Attempt |
|--------|--------|---------------|----------------|-------------------|---------------|
| Gurobipy | INFEASIBLE | N/A | 0.39s | N/A | 4 |
| Docplex | INFEASIBLE | N/A | 1.34s | N/A | 4 |
| Pyomo | INFEASIBLE | N/A | 1.37s | N/A | 4 |

### Solver Consistency Analysis
**Result**: All solvers produced consistent results ✓
**Consistent Solvers**: gurobipy, docplex, pyomo
**Solver Retry Summary**: gurobipy: 4 attempts, docplex: 4 attempts, pyomo: 4 attempts

### Final Recommendation
**Confidence Level**: HIGH
**Preferred Solver(s)**: gurobipy
**Reasoning**: Gurobipy provided the fastest and most reliable infeasibility diagnosis. Its efficiency and robustness make it the preferred solver for this analysis.

### Business Interpretation
**Overall Strategy**: The problem is infeasible, meaning the current constraints and data inputs do not allow for a valid solution. This suggests that the staffing or time allocation requirements are unrealistic or conflicting.
**Objective Value Meaning**: The objective value represents the total cost of handling complaints. Since the problem is infeasible, no cost can be calculated.
**Resource Allocation Summary**: No valid resource allocation is possible under the current constraints. Re-evaluate the constraints or data inputs to identify feasible adjustments.
**Implementation Recommendations**: 1. Review and relax constraints (e.g., min_time, max_time, max_hours) to make the problem feasible. 2. Verify data inputs for consistency and realism. 3. Consider revising the model formulation to address potential logical errors.