#!/usr/bin/env python3
"""
DOCPLEX Implementation for Customer Card Transactions Optimization
"""

from docplex.mp.model import Model

def optimize_transaction_fees():
    """Optimize transaction fees by allocating amounts across card types."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="customers_card_transactions")
    
    # Data from the problem
    card_types = ['VISA', 'MASTERCARD', 'AMEX']
    card_fees = {'VISA': 0.02, 'MASTERCARD': 0.03, 'AMEX': 0.035}
    customers = [1, 2, 3]
    account_limits = {1: 1000, 2: 1500, 3: 2000}
    
    # Validate array lengths
    assert len(card_types) == len(card_fees), "Card types and fees mismatch"
    assert len(customers) == len(account_limits), "Customers and limits mismatch"
    
    # 2. VARIABLES
    # Decision variables: x[i][j] = transaction amount for customer i on card j
    x = {(i, j): mdl.continuous_var(name=f"x_{i}_{j}", lb=0) 
         for i in customers for j in card_types}
    
    # 3. OBJECTIVE FUNCTION
    # Minimize total transaction fees
    total_fees = mdl.sum(card_fees[j] * x[i, j] for i in customers for j in card_types)
    mdl.minimize(total_fees)
    
    # 4. CONSTRAINTS
    # Ensure total transaction amount per customer does not exceed account limit
    for i in customers:
        total_transaction = mdl.sum(x[i, j] for j in card_types)
        mdl.add_constraint(total_transaction <= account_limits[i], ctname=f"limit_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in customers:
            for j in card_types:
                value = solution.get_value(x[i, j])
                if value > 1e-6:
                    print(f"Customer {i}, Card {j}: {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization
if __name__ == "__main__":
    optimize_transaction_fees()