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

from docplex.mp.model import Model

def optimize_resource_allocation():
    """Optimize resource allocation to minimize total casualties."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="Resource_Allocation")
    
    # 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_per_location = 30
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(locations) == len(casualties_coeff), "Array length mismatch"
    safe_range = range(min(len(locations), len(casualties_coeff)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables: resources allocated to each location
    x = {i: mdl.continuous_var(name=f"x_{i}", lb=0) for i in locations}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize total casualties: Z = 30x1 + 18x2 + 11x3
    objective = mdl.sum(casualties_coeff[i] * x[i] for i in locations)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    
    # Total Resource Constraint: x1 + x2 + x3 <= 45
    total_resource_usage = mdl.sum(x[i] for i in locations)
    mdl.add_constraint(total_resource_usage <= total_resources, ctname="total_resources")
    
    # Maximum Casualties Constraint: 30x1 <= 30, 18x2 <= 30, 11x3 <= 30
    for i in locations:
        mdl.add_constraint(casualties_coeff[i] * x[i] <= max_casualties_per_location, ctname=f"max_casualties_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in locations:
            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
if __name__ == "__main__":
    optimize_resource_allocation()