# Complete DOCPLEX implementation - Retry Attempt 4

from docplex.mp.model import Model

def optimize_police_allocation():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="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"
    
    safe_range = range(n_counties)  # Safe indexing
    
    # 2. VARIABLES
    x = {i: mdl.integer_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    objective = mdl.sum(crime_rates[i] * x[i] for i in safe_range)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    # Total Officers Constraint
    mdl.add_constraint(mdl.sum(x[i] for i in safe_range) <= total_officers, ctname="total_officers")
    
    # Minimum Officers per County
    for i in safe_range:
        mdl.add_constraint(x[i] >= min_officers[i], ctname=f"min_officers_{i}")
    
    # Residents per Officer Constraint
    for i in safe_range:
        mdl.add_constraint(x[i] <= populations[i] // residents_per_officer[i], ctname=f"residents_per_officer_{i}")
    
    # Case Burden Constraint
    for i in safe_range:
        mdl.add_constraint(x[i] >= case_burdens[i] / max_case_burden, ctname=f"case_burden_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(x[i])
            if value > 1e-6:
                print(f"x[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

    return mdl

# Execute the optimization
optimize_police_allocation()