# Complete PYOMO implementation

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

def optimize_insurance_settlements():
    """Optimize insurance claim settlements to minimize total cost while adhering to constraints."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Claims data
    claims_data = {
        1: 15000,
        2: 25000,
        3: 35000
    }
    
    # Budget data
    total_budget = 500000
    max_settlement_per_claim = 50000
    min_settlement_percentage = 0.5
    
    # Validate array lengths before indexing
    assert len(claims_data) > 0, "Claims data is empty"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=claims_data.keys())  # Set of claim IDs
    
    # 4. PARAMETERS (data containers)
    model.amount_claimed = pyo.Param(model.I, initialize=claims_data)
    model.total_budget = pyo.Param(initialize=total_budget)
    model.max_settlement_per_claim = pyo.Param(initialize=max_settlement_per_claim)
    model.min_settlement_percentage = pyo.Param(initialize=min_settlement_percentage)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.minimize)
    
    # 7. CONSTRAINTS
    # Total Budget Constraint
    def total_budget_rule(model):
        return sum(model.x[i] for i in model.I) <= model.total_budget
    model.total_budget_constraint = pyo.Constraint(rule=total_budget_rule)
    
    # Maximum Settlement per Claim
    def max_settlement_rule(model, i):
        return model.x[i] <= model.max_settlement_per_claim
    model.max_settlement_constraint = pyo.Constraint(model.I, rule=max_settlement_rule)
    
    # Minimum Settlement Percentage
    def min_settlement_rule(model, i):
        return model.x[i] >= model.min_settlement_percentage * model.amount_claimed[i]
    model.min_settlement_constraint = pyo.Constraint(model.I, rule=min_settlement_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)}")
        
        # Extract variable values
        print("\nSettlement amounts:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"Claim {i}: {x_val:.2f}")
        
    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_insurance_settlements()