# Complete PYOMO implementation

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

def small_bank_optimization():
    """Optimize fund allocation between savings and checking accounts for a small bank."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Customer IDs and their total funds
    customer_ids = [1, 2, 3]
    total_funds = {1: 1000.0, 2: 1500.0, 3: 2000.0}
    
    # Interest rates
    savings_interest_rate = 0.03
    checking_interest_rate = 0.01
    
    # Minimum and maximum balances
    min_savings_balance = 100
    min_checking_balance = 50
    max_savings_balance = 50000
    max_checking_balance = 30000
    
    # Total bank funds
    total_bank_funds = 1000000
    
    # CRITICAL: Validate array lengths before indexing
    assert len(customer_ids) == len(total_funds), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=customer_ids)  # Set of customers
    
    # 4. PARAMETERS
    model.total_funds = pyo.Param(model.I, initialize=total_funds)
    
    # 5. VARIABLES
    model.s = pyo.Var(model.I, within=pyo.NonNegativeReals, bounds=(min_savings_balance, max_savings_balance))  # Savings balance
    model.c = pyo.Var(model.I, within=pyo.NonNegativeReals, bounds=(min_checking_balance, max_checking_balance))  # Checking balance
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return savings_interest_rate * sum(model.s[i] for i in model.I) + checking_interest_rate * sum(model.c[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total Funds Constraint
    def total_funds_rule(model, i):
        return model.s[i] + model.c[i] <= model.total_funds[i]
    model.total_funds_constraint = pyo.Constraint(model.I, rule=total_funds_rule)
    
    # Total Bank Funds Constraint
    def total_bank_funds_rule(model):
        return sum(model.s[i] for i in model.I) + sum(model.c[i] for i in model.I) <= total_bank_funds
    model.total_bank_funds_constraint = pyo.Constraint(rule=total_bank_funds_rule)
    
    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')
    
    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap
    
    # Solve the model
    results = solver.solve(model, tee=True)  # tee=True shows solver output
    
    # 9. RESULT PROCESSING
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nVariable values:")
        for i in model.I:
            s_val = pyo.value(model.s[i])
            c_val = pyo.value(model.c[i])
            print(f"Customer {i}: Savings = {s_val:.2f}, Checking = {c_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
if __name__ == "__main__":
    small_bank_optimization()