# Complete PYOMO implementation

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

def casualty_minimization():
    """Optimize resource allocation to minimize casualties"""

    # 1. MODEL CREATION
    model = pyo.ConcreteModel()

    # 2. DATA SETUP
    # Coefficients for the objective function
    killed = [10, 5, 20]
    injured = [50, 30, 100]
    costs = [2000, 1500, 2500]
    total_budget = 1000000  # Example budget

    # Validate array lengths
    n_locations = len(killed)
    assert len(injured) == len(costs) == n_locations, "Array length mismatch"

    # 3. SETS
    model.Locations = pyo.RangeSet(1, n_locations)

    # 4. PARAMETERS
    model.killed = pyo.Param(model.Locations, initialize={i+1: killed[i] for i in range(n_locations)})
    model.injured = pyo.Param(model.Locations, initialize={i+1: injured[i] for i in range(n_locations)})
    model.cost = pyo.Param(model.Locations, initialize={i+1: costs[i] for i in range(n_locations)})

    # 5. VARIABLES
    model.x = pyo.Var(model.Locations, within=pyo.NonNegativeReals)

    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum((model.killed[i] + model.injured[i]) * model.x[i] for i in model.Locations)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)

    # 7. CONSTRAINTS
    def budget_constraint_rule(model):
        return sum(model.cost[i] * model.x[i] for i in model.Locations) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_constraint_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)

    # 9. RESULT PROCESSING
    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.Locations:
            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
casualty_minimization()