#!/usr/bin/env python3
"""
DOCPLEX implementation for insurance_policies optimization problem
"""

from docplex.mp.model import Model

def optimize_insurance_settlements():
    """Optimize insurance settlements to minimize total cost while adhering to constraints."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="insurance_policies")
    
    # Data from the problem
    claims = [
        {"Claim_ID": 1, "Amount_Claimed": 15000},
        {"Claim_ID": 2, "Amount_Claimed": 25000},
        {"Claim_ID": 3, "Amount_Claimed": 35000}
    ]
    budgets = {"Total_Budget": 500000, "Maximum_Settlement_Per_Claim": 50000}
    
    # Extract data into lists for easier access
    claim_ids = [claim["Claim_ID"] for claim in claims]
    amounts_claimed = [claim["Amount_Claimed"] for claim in claims]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(claim_ids) == len(amounts_claimed), "Array length mismatch"
    safe_range = range(min(len(claim_ids), len(amounts_claimed)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables: settlement amount for each claim
    x = {i: mdl.continuous_var(name=f"x_{claim_ids[i]}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total settlement cost
    objective = mdl.sum(x[i] for i in safe_range)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS
    
    # Total Budget Constraint
    total_settlement = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_settlement <= budgets["Total_Budget"], ctname="total_budget")
    
    # Maximum Settlement per Claim
    for i in safe_range:
        mdl.add_constraint(x[i] <= budgets["Maximum_Settlement_Per_Claim"], ctname=f"max_settlement_{claim_ids[i]}")
    
    # Minimum Settlement Percentage (50% of claimed amount)
    for i in safe_range:
        mdl.add_constraint(x[i] >= 0.5 * amounts_claimed[i], ctname=f"min_settlement_{claim_ids[i]}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(x[i])
            print(f"Settlement for Claim {claim_ids[i]}: {value:.2f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

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