#!/usr/bin/env python3
"""
DOCplex implementation for county_public_safety optimization problem
"""

from docplex.mp.model import Model

def optimize_police_allocation():
    """Optimize police officer allocation across counties to minimize crime rate"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="county_public_safety")
    
    # Data from the problem
    counties = [1, 2, 3]
    crime_rates = {1: 0.05, 2: 0.1, 3: 0.15}
    populations = {1: 10000, 2: 20000, 3: 30000}
    min_police = {1: 10, 2: 20, 3: 30}
    max_police = {1: 100, 2: 200, 3: 300}
    total_police_available = 300
    max_case_burden = 200
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(counties) == len(crime_rates) == len(populations) == len(min_police) == len(max_police), "Array length mismatch"
    safe_range = range(min(len(counties), len(crime_rates), len(populations), len(min_police), len(max_police)))  # Safe indexing
    
    # 2. VARIABLES
    x = {i: mdl.integer_var(name=f"x_{i}", lb=min_police[i], ub=max_police[i]) 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 Police Officers Constraint
    total_police = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_police <= total_police_available, ctname="total_police_limit")
    
    # Case Burden Constraint
    for i in safe_range:
        mdl.add_constraint(populations[i] <= max_case_burden * x[i], 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])
            print(f"Police officers in county {i}: {value}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

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