# Complete GUROBIPY implementation

import gurobipy as gp
from gurobipy import GRB

def optimize_credit_limits():
    """Optimize credit limits to maximize expected transaction volume."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("customers_card_transactions")
    
    # Data from the database
    account_ids = [1, 2, 3]
    expected_volumes = [1200.0, 1800.0, 2200.0]
    max_credit_limits = [2000.0, 2500.0, 3000.0]
    is_active = [True, True, True]
    
    # Business configuration parameters
    Total_Available_Credit = 5000.0
    Minimum_Credit_Limit = 500.0
    
    # CRITICAL: Validate array lengths before loops
    assert len(account_ids) == len(expected_volumes) == len(max_credit_limits) == len(is_active), "Array length mismatch"
    
    # 2. VARIABLES
    # Variable dictionaries for credit limits
    x = {i: model.addVar(vtype=GRB.CONTINUOUS, name=f"x_{account_ids[i]}", lb=0) 
         for i in range(len(account_ids))}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total expected transaction volume
    model.setObjective(gp.quicksum(expected_volumes[i] * x[i] for i in range(len(account_ids))), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total credit allocated must not exceed the total available credit
    model.addConstr(gp.quicksum(x[i] for i in range(len(account_ids))) <= Total_Available_Credit, name="total_credit_limit")
    
    # Each account's credit limit must not exceed its maximum allowable credit limit
    for i in range(len(account_ids)):
        model.addConstr(x[i] <= max_credit_limits[i], name=f"max_credit_limit_{account_ids[i]}")
    
    # For an account to be considered active, its credit limit must meet or exceed the minimum credit limit requirement
    for i in range(len(account_ids)):
        if is_active[i]:
            model.addConstr(x[i] >= Minimum_Credit_Limit, name=f"min_credit_limit_{account_ids[i]}")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(len(account_ids)):
            if x[i].x > 1e-6:
                print(f"x[{account_ids[i]}] = {x[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_credit_limits()