#!/usr/bin/env python3
"""
Gurobipy 12.0.2 Implementation for County Public Safety Optimization
"""

import gurobipy as gp
from gurobipy import GRB

def optimize_police_allocation():
    """Optimize police officer allocation across counties to minimize crime rate."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("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}
    max_case_burden = 200
    
    # Total police officers available
    total_police = 300
    
    # CRITICAL: Validate array lengths before loops
    assert len(counties) == len(crime_rates) == len(populations) == len(min_police) == len(max_police), "Array length mismatch"
    
    # 2. VARIABLES
    # Decision variables: number of police officers allocated to each county
    x = {i: model.addVar(vtype=GRB.INTEGER, name=f"x_{i}", lb=min_police[i], ub=max_police[i]) 
         for i in counties}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total crime rate across all counties
    model.setObjective(gp.quicksum(crime_rates[i] * x[i] for i in counties), GRB.MINIMIZE)
    
    # 4. CONSTRAINTS
    
    # Total Police Officers Constraint
    model.addConstr(gp.quicksum(x[i] for i in counties) <= total_police, name="total_police_limit")
    
    # Case Burden Constraint
    for i in counties:
        model.addConstr(populations[i] <= max_case_burden * x[i], name=f"case_burden_{i}")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in counties:
            print(f"Police officers in county {i}: {x[i].x}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

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