# Complete PYOMO implementation

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

def optimize_police_allocation():
    """Optimize police officer allocation across counties to minimize crime rate."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    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 = 300
    max_case_burden = 200
    
    # CRITICAL: Validate array lengths before indexing
    assert len(counties) == len(crime_rates) == len(populations) == len(min_police) == len(max_police), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=counties)
    
    # 4. PARAMETERS
    model.crime_rate = pyo.Param(model.I, initialize=crime_rates)
    model.population = pyo.Param(model.I, initialize=populations)
    model.min_police = pyo.Param(model.I, initialize=min_police)
    model.max_police = pyo.Param(model.I, initialize=max_police)
    model.total_police = pyo.Param(initialize=total_police)
    model.max_case_burden = pyo.Param(initialize=max_case_burden)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeIntegers)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.crime_rate[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Total Police Officers Constraint
    def total_police_rule(model):
        return sum(model.x[i] for i in model.I) <= model.total_police
    model.total_police_constraint = pyo.Constraint(rule=total_police_rule)
    
    # Minimum Police Officers Constraint
    def min_police_rule(model, i):
        return model.x[i] >= model.min_police[i]
    model.min_police_constraint = pyo.Constraint(model.I, rule=min_police_rule)
    
    # Maximum Police Officers Constraint
    def max_police_rule(model, i):
        return model.x[i] <= model.max_police[i]
    model.max_police_constraint = pyo.Constraint(model.I, rule=max_police_rule)
    
    # Case Burden Constraint
    def case_burden_rule(model, i):
        return model.population[i] <= model.max_case_burden * model.x[i]
    model.case_burden_constraint = pyo.Constraint(model.I, rule=case_burden_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("\nPolice officer allocation:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            print(f"County {i}: {x_val} officers")
        
    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

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