# Complete PYOMO implementation

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

def optimize_credit_limits():
    """Optimize credit limits to maximize expected transaction volume."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the problem context
    account_ids = [1, 2, 3]
    expected_volumes = {1: 1200.0, 2: 1800.0, 3: 2200.0}
    max_credit_limits = {1: 2000.0, 2: 2500.0, 3: 3000.0}
    is_active = {1: True, 2: True, 3: True}
    
    # Business configuration parameters
    Total_Available_Credit = 5000.0
    Minimum_Credit_Limit = 500.0
    
    # CRITICAL: Validate array lengths before indexing
    assert len(expected_volumes) == len(max_credit_limits) == len(is_active) == len(account_ids), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=account_ids)
    
    # 4. PARAMETERS
    model.expected_volume = pyo.Param(model.I, initialize=expected_volumes)
    model.max_credit_limit = pyo.Param(model.I, initialize=max_credit_limits)
    model.is_active = pyo.Param(model.I, initialize=is_active)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.expected_volume[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total credit constraint
    def total_credit_rule(model):
        return sum(model.x[i] for i in model.I) <= Total_Available_Credit
    model.total_credit_constraint = pyo.Constraint(rule=total_credit_rule)
    
    # Maximum credit limit constraint
    def max_credit_limit_rule(model, i):
        return model.x[i] <= model.max_credit_limit[i]
    model.max_credit_limit_constraint = pyo.Constraint(model.I, rule=max_credit_limit_rule)
    
    # Minimum credit limit for active accounts
    def min_credit_limit_rule(model, i):
        if model.is_active[i]:
            return model.x[i] >= Minimum_Credit_Limit
        else:
            return pyo.Constraint.Skip
    model.min_credit_limit_constraint = pyo.Constraint(model.I, rule=min_credit_limit_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)
    
    # 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):.2f}")
        
        # Extract variable values
        print("\nVariable values:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"x[{i}] = {x_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
optimize_credit_limits()