# Complete DOCPLEX implementation

from docplex.mp.model import Model
from datetime import datetime

def optimize_claim_settlements():
    """Optimize insurance claim settlements to minimize total payouts."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="insurance_policies")
    
    # Sample data from the Claims table
    amount_claimed = [1200.0, 1600.0, 2500.0]
    date_claim_received = [
        datetime(2023, 1, 1),
        datetime(2023, 2, 1),
        datetime(2023, 3, 1)
    ]
    date_claim_settled = [
        datetime(2023, 1, 15),
        datetime(2023, 2, 20),
        datetime(2023, 3, 10)
    ]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(amount_claimed) == len(date_claim_received) == len(date_claim_settled), "Array length mismatch"
    safe_range = range(min(len(amount_claimed), len(date_claim_received), len(date_claim_settled)))  # Safe indexing
    
    # 2. VARIABLES
    # Variable dictionaries (most common)
    x = {i: mdl.continuous_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize the total amount settled across all claims
    objective = mdl.sum(x[i] for i in safe_range)
    mdl.minimize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Pattern A: Maximum Amount Claimed Constraint
    for i in safe_range:
        mdl.add_constraint(x[i] <= amount_claimed[i], ctname=f"max_claim_{i}")
    
    # Pattern B: Settlement Period Constraint
    for i in safe_range:
        settlement_period = (date_claim_settled[i] - date_claim_received[i]).days
        mdl.add_constraint(settlement_period <= 30, ctname=f"settlement_period_{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])
            if value > 1e-6:
                print(f"x[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization
optimize_claim_settlements()