#!/usr/bin/env python3
"""
Gurobipy 12.0.2 Implementation for Insurance Policy Optimization Problem
"""

import gurobipy as gp
from gurobipy import GRB

def optimize_insurance_settlements():
    """Optimize insurance settlements to minimize total cost while adhering to constraints."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("insurance_policies")
    
    # Data from the problem
    claims = {
        1: 15000,
        2: 25000,
        3: 35000
    }
    total_budget = 500000
    max_settlement_per_claim = 50000
    min_settlement_percentage = 0.5
    
    # CRITICAL: Validate array lengths before loops
    claim_ids = list(claims.keys())
    n_claims = len(claim_ids)
    assert n_claims > 0, "No claims provided"
    
    # 2. VARIABLES
    # Decision variables: settlement amount for each claim
    x = {i: model.addVar(vtype=GRB.CONTINUOUS, name=f"x_{i}", lb=0) 
         for i in claim_ids}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total settlement cost
    model.setObjective(gp.quicksum(x[i] for i in claim_ids), GRB.MINIMIZE)
    
    # 4. CONSTRAINTS
    
    # Total Budget Constraint
    model.addConstr(gp.quicksum(x[i] for i in claim_ids) <= total_budget, name="total_budget")
    
    # Maximum Settlement per Claim
    for i in claim_ids:
        model.addConstr(x[i] <= max_settlement_per_claim, name=f"max_settlement_{i}")
    
    # Minimum Settlement Percentage
    for i in claim_ids:
        model.addConstr(x[i] >= min_settlement_percentage * claims[i], name=f"min_settlement_{i}")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in claim_ids:
            print(f"Settlement for claim {i}: {x[i].x:.2f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

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