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

import gurobipy as gp
from gurobipy import GRB

def optimize_transaction_fees():
    """Optimize transaction fees by allocating transactions across card types."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("customer_card_transactions")
    
    # Data from the problem
    card_types = ['VISA', 'MASTERCARD', 'AMEX']
    customers = [1, 2, 3]
    card_fees = {'VISA': 0.02, 'MASTERCARD': 0.03, 'AMEX': 0.035}
    account_limits = {1: 1000, 2: 1500, 3: 2000}
    
    # CRITICAL: Validate array lengths before loops
    assert len(card_types) == len(card_fees), "Card types and fees length mismatch"
    assert len(customers) == len(account_limits), "Customers and account limits length mismatch"
    
    # 2. VARIABLES
    # Decision variables: x[i,j] = transaction amount for customer i on card type j
    x = model.addVars(customers, card_types, vtype=GRB.CONTINUOUS, name="x", lb=0)
    
    # 3. OBJECTIVE FUNCTION
    # Minimize total transaction fees
    model.setObjective(
        gp.quicksum(card_fees[j] * x[i, j] for i in customers for j in card_types),
        GRB.MINIMIZE
    )
    
    # 4. CONSTRAINTS
    # Ensure total transaction amount per customer does not exceed account limit
    for i in customers:
        model.addConstr(
            gp.quicksum(x[i, j] for j in card_types) <= account_limits[i],
            name=f"account_limit_{i}"
        )
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in customers:
            for j in card_types:
                if x[i, j].x > 1e-6:
                    print(f"x[{i},{j}] = {x[i, j].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

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