# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_credit_limits():
    # 1. MODEL & DATA SETUP
    mdl = Model(name="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 to prevent IndexError
    assert len(account_ids) == len(expected_volumes) == len(max_credit_limits) == len(is_active), "Array length mismatch"
    safe_range = range(len(account_ids))  # Safe indexing

    # 2. VARIABLES
    # Variable dictionaries (most common)
    x = {i: mdl.continuous_var(name=f"x_{account_ids[i]}", lb=0) for i in safe_range}

    # 3. OBJECTIVE FUNCTION
    # Use mdl.sum() for summations (DOCplex specific)
    objective = mdl.sum(expected_volumes[i] * x[i] for i in safe_range)
    mdl.maximize(objective)

    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS

    # Total credit allocated across all accounts must not exceed the total available credit
    total_credit_usage = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_credit_usage <= Total_Available_Credit, ctname="total_credit_limit")

    # Each account's credit limit must not exceed its maximum allowable credit limit
    for i in safe_range:
        mdl.add_constraint(x[i] <= max_credit_limits[i], ctname=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 safe_range:
        if is_active[i]:
            mdl.add_constraint(x[i] >= Minimum_Credit_Limit, ctname=f"min_credit_limit_{account_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])
            if value > 1e-6:
                print(f"x[{account_ids[i]}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

    return mdl

# Run the optimization
optimize_credit_limits()