# Complete GUROBIPY implementation - Retry Attempt 4

import gurobipy as gp
from gurobipy import GRB

def optimize_police_allocation():
    # 1. MODEL & DATA SETUP
    model = gp.Model("county_public_safety")
    
    # Data from the database
    crime_rates = [0.15, 0.25, 0.18, 0.22, 0.2]
    populations = [1500, 2500, 1800, 2200, 2000]
    residents_per_officer = [150, 125, 180, 110, 100]
    case_burdens = [7.0, 12.0, 9.0, 11.0, 10.0]
    min_officers = [10, 20, 12, 18, 15]
    
    # Business configuration parameters
    total_officers = 75
    max_case_burden = 15.0
    
    # Validate array lengths
    n_counties = len(crime_rates)
    assert len(populations) == len(residents_per_officer) == len(case_burdens) == len(min_officers) == n_counties, "Array length mismatch"
    
    # 2. VARIABLES
    x = model.addVars(n_counties, vtype=GRB.INTEGER, name="x", lb=0)
    
    # 3. OBJECTIVE FUNCTION
    model.setObjective(gp.quicksum(crime_rates[i] * x[i] for i in range(n_counties)), GRB.MINIMIZE)
    
    # 4. CONSTRAINTS
    # Total Officers Constraint
    model.addConstr(gp.quicksum(x[i] for i in range(n_counties)) <= total_officers, name="total_officers")
    
    # Minimum Officers per County
    model.addConstrs((x[i] >= min_officers[i] for i in range(n_counties)), name="min_officers")
    
    # Residents per Officer Constraint
    model.addConstrs((x[i] <= populations[i] // residents_per_officer[i] for i in range(n_counties)), name="residents_per_officer")
    
    # Case Burden Constraint
    model.addConstrs((x[i] >= case_burdens[i] / max_case_burden for i in range(n_counties)), name="case_burden")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_counties):
            print(f"x[{i}] = {x[i].x:.0f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Run the optimization
optimize_police_allocation()