#!/usr/bin/env python3
"""
Gurobipy Implementation for Security Agency Resource Allocation Problem
"""

import gurobipy as gp
from gurobipy import GRB

def optimize_resource_allocation():
    """Optimize resource allocation to minimize casualties across locations."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("ResourceAllocation")
    
    # Data from the problem
    locations = [1, 2, 3]
    casualties_coeff = {1: 30, 2: 18, 3: 11}  # Sum of killed and injured per location
    total_resources = 45
    max_casualties = 30
    
    # CRITICAL: Validate array lengths before loops
    assert len(locations) == len(casualties_coeff), "Array length mismatch"
    
    # 2. VARIABLES
    x = {i: model.addVar(vtype=GRB.CONTINUOUS, name=f"x_{i}", lb=0) for i in locations}
    
    # 3. OBJECTIVE FUNCTION
    model.setObjective(gp.quicksum(casualties_coeff[i] * x[i] for i in locations), GRB.MINIMIZE)
    
    # 4. CONSTRAINTS
    
    # Total Resource Constraint
    model.addConstr(gp.quicksum(x[i] for i in locations) <= total_resources, name="total_resources")
    
    # Maximum Casualties Constraint
    for i in locations:
        model.addConstr(casualties_coeff[i] * x[i] <= max_casualties, name=f"max_casualties_{i}")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in locations:
            if x[i].x > 1e-6:
                print(f"Resources allocated to location {i}: {x[i].x:.3f}")
    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_resource_allocation()