# Complete PYOMO implementation

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

def storm_record_optimization():
    """Optimization for resource allocation to minimize storm damage cost"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    n_regions = 3
    damage_costs = [12.0, 25.0, 18.0]
    max_speeds = [110.0, 140.0, 130.0]
    cities_affected = [4, 6, 5]
    total_resources = 600.0
    
    # CRITICAL: Validate array lengths before indexing
    assert len(damage_costs) == len(max_speeds) == len(cities_affected) == n_regions, "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_regions)  # 1-based indexing
    
    # 4. PARAMETERS
    model.damage_cost = pyo.Param(model.I, initialize={i+1: damage_costs[i] for i in range(n_regions)})
    model.max_speed = pyo.Param(model.I, initialize={i+1: max_speeds[i] for i in range(n_regions)})
    model.cities_affected = pyo.Param(model.I, initialize={i+1: cities_affected[i] for i in range(n_regions)})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.damage_cost[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Total resource availability constraint
    def total_resource_constraint_rule(model):
        return sum(model.x[i] for i in model.I) <= total_resources
    model.total_resource_constraint = pyo.Constraint(rule=total_resource_constraint_rule)
    
    # Resource allocation constraints based on storm severity
    def resource_allocation_rule(model, i):
        return model.x[i] <= model.cities_affected[i] * model.max_speed[i]
    model.resource_allocation_constraint = pyo.Constraint(model.I, rule=resource_allocation_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):.3f}")
        
        # Extract variable values
        print("\nVariable values:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {x_val:.3f}")
        
    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
storm_record_optimization()