# Complete PYOMO implementation

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

def insurance_policies_optimization():
    """Optimize insurance claim settlements to minimize total payouts."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the provided SQL data
    amount_claimed = [1200.0, 1600.0, 2500.0]
    date_claim_received = ["2023-01-01", "2023-02-01", "2023-03-01"]
    date_claim_settled = ["2023-01-15", "2023-02-20", "2023-03-10"]
    
    # Convert date strings to datetime objects for calculation
    date_claim_received = [datetime.strptime(date, "%Y-%m-%d") for date in date_claim_received]
    date_claim_settled = [datetime.strptime(date, "%Y-%m-%d") for date in date_claim_settled]
    
    # Calculate settlement periods
    settlement_periods = [(settled - received).days for settled, received in zip(date_claim_settled, date_claim_received)]
    
    # CRITICAL: Validate array lengths before indexing
    n_claims = len(amount_claimed)
    assert len(settlement_periods) == n_claims, "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.RangeSet(1, n_claims)  # 1-based indexing
    
    # 4. PARAMETERS
    model.amount_claimed = pyo.Param(model.I, initialize={i+1: amount_claimed[i] for i in range(n_claims)})
    model.settlement_periods = pyo.Param(model.I, initialize={i+1: settlement_periods[i] for i in range(n_claims)})
    
    # 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
    # Maximum Amount Claimed Constraint
    def max_claimed_rule(model, i):
        return model.x[i] <= model.amount_claimed[i]
    model.max_claimed_constraint = pyo.Constraint(model.I, rule=max_claimed_rule)
    
    # Settlement Period Constraint
    def settlement_period_rule(model, i):
        return model.settlement_periods[i] <= 30
    model.settlement_period_constraint = pyo.Constraint(model.I, rule=settlement_period_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Solve the model
    results = solver.solve(model, tee=True)
    
    # 9. RESULT PROCESSING
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective):.2f}")
        
        # Extract variable values
        print("\nVariable values:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{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

# Run the optimization
insurance_policies_optimization()