# Complete PYOMO implementation

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

def optimize_resource_allocation():
    """Optimize resource allocation to minimize casualties across locations."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    locations = [1, 2, 3]
    casualties_coeff = {1: 30, 2: 18, 3: 11}  # Coefficients from objective function
    total_resources = 45
    max_casualties = 30
    
    # CRITICAL: Validate array lengths before indexing
    assert len(locations) == len(casualties_coeff), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=locations)  # Set of locations
    
    # 4. PARAMETERS (data containers)
    model.casualties_coeff = pyo.Param(model.I, initialize=casualties_coeff)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)  # Resources allocated to each location
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.casualties_coeff[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    
    # Total Resource Constraint
    def total_resource_rule(model):
        return sum(model.x[i] for i in model.I) <= total_resources
    model.total_resource_constraint = pyo.Constraint(rule=total_resource_rule)
    
    # Maximum Casualties Constraint
    def max_casualties_rule(model, i):
        return model.casualties_coeff[i] * model.x[i] <= max_casualties
    model.max_casualties_constraint = pyo.Constraint(model.I, rule=max_casualties_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nResource Allocation:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"Location {i}: {x_val:.3f} resources")
        
    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

# Execute the optimization
if __name__ == "__main__":
    optimize_resource_allocation()