# Complete GUROBIPY implementation

import gurobipy as gp
from gurobipy import GRB
from datetime import datetime

def optimize_claim_settlements():
    """Optimize insurance claim settlements using Gurobi"""

    # 1. MODEL & DATA SETUP
    model = gp.Model("insurance_policies")

    # Sample data based on the provided SQL schema and data
    claims_data = [
        {"Amount_Claimed": 1200.0, "Date_Claim_Received": "2023-01-01", "Date_Claim_Settled": "2023-01-15"},
        {"Amount_Claimed": 1600.0, "Date_Claim_Received": "2023-02-01", "Date_Claim_Settled": "2023-02-20"},
        {"Amount_Claimed": 2500.0, "Date_Claim_Received": "2023-03-01", "Date_Claim_Settled": "2023-03-10"}
    ]

    n_claims = len(claims_data)

    # CRITICAL: Validate array lengths before loops
    assert n_claims > 0, "No claims data available"

    # 2. VARIABLES
    # Variable dictionaries for Amount_Settled
    Amount_Settled = {i: model.addVar(vtype=GRB.CONTINUOUS, name=f"Amount_Settled_{i}", lb=0)
                      for i in range(n_claims)}

    # 3. OBJECTIVE FUNCTION
    # Minimize the total amount settled
    model.setObjective(gp.quicksum(Amount_Settled[i] for i in range(n_claims)), GRB.MINIMIZE)

    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS

    # Maximum Amount Claimed Constraint
    for i in range(n_claims):
        model.addConstr(Amount_Settled[i] <= claims_data[i]["Amount_Claimed"], name=f"max_claimed_{i}")

    # Settlement Period Constraint
    for i in range(n_claims):
        date_received = datetime.strptime(claims_data[i]["Date_Claim_Received"], "%Y-%m-%d")
        date_settled = datetime.strptime(claims_data[i]["Date_Claim_Settled"], "%Y-%m-%d")
        settlement_period = (date_settled - date_received).days
        model.addConstr(settlement_period <= 30, name=f"settlement_period_{i}")

    # 5. SOLVING & RESULTS
    model.optimize()

    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_claims):
            if Amount_Settled[i].x > 1e-6:
                print(f"Amount_Settled[{i}] = {Amount_Settled[i].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")

    return model

# Run the optimization
optimize_claim_settlements()