# Complete DOCPLEX implementation

from docplex.mp.model import Model

def storm_resource_optimization():
    """Optimize resource allocation to minimize storm damage costs."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="storm_record")
    
    # Data from the problem context
    damage_costs = [12.0, 25.0, 18.0]
    max_speeds = [110.0, 140.0, 130.0]
    cities_affected = [4, 6, 5]
    total_resources_available = 600.0
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(damage_costs) == len(max_speeds) == len(cities_affected), "Array length mismatch"
    safe_range = range(min(len(damage_costs), len(max_speeds), len(cities_affected)))  # Safe indexing
    
    # 2. VARIABLES
    x = {i: mdl.continuous_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    objective = mdl.sum(damage_costs[i] * x[i] for i in safe_range)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total resource availability constraint
    total_usage = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_usage <= total_resources_available, ctname="total_resource_limit")
    
    # Resource allocation constraints based on storm severity
    for i in safe_range:
        max_allocation = cities_affected[i] * max_speeds[i]
        mdl.add_constraint(x[i] <= max_allocation, ctname=f"severity_limit_{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])
            if value > 1e-6:
                print(f"x[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
storm_resource_optimization()