# Complete PYOMO implementation

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

def loan_optimization():
    """Optimize loan allocation to maximize total disbursement while adhering to constraints."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Loan amounts (decision variables)
    loan_amounts = [5000.0, 10000.0, 7500.0]
    # Number of customers per branch
    no_of_customers = [150, 250, 200]
    # Customer credit scores
    credit_scores = [720, 780, 750]
    
    # CRITICAL: Validate array lengths before indexing
    assert len(loan_amounts) == len(no_of_customers) == len(credit_scores), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    n_loans = len(loan_amounts)
    model.L = pyo.RangeSet(1, n_loans)  # 1-based indexing for loans
    
    # 4. PARAMETERS (data containers)
    model.loan_amount = pyo.Param(model.L, initialize={i+1: loan_amounts[i] for i in range(n_loans)})
    model.no_of_customers = pyo.Param(model.L, initialize={i+1: no_of_customers[i] for i in range(n_loans)})
    model.credit_score = pyo.Param(model.L, initialize={i+1: credit_scores[i] for i in range(n_loans)})
    
    # 5. VARIABLES
    # Continuous variables for loan amounts to be disbursed
    model.amount = pyo.Var(model.L, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    # Maximize the total loan amount disbursed
    def obj_rule(model):
        return sum(model.amount[i] for i in model.L)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Constraint 1: Branch customer capacity
    def branch_capacity_rule(model, i):
        return model.amount[i] <= model.no_of_customers[i] * 15000
    model.branch_capacity_constraint = pyo.Constraint(model.L, rule=branch_capacity_rule)
    
    # Constraint 2: Customer credit score
    def credit_score_rule(model, i):
        return model.amount[i] <= model.credit_score[i] * 600
    model.credit_score_constraint = pyo.Constraint(model.L, rule=credit_score_rule)
    
    # Constraint 3: Total loan exposure per customer
    def total_exposure_rule(model, i):
        return model.amount[i] <= 60000
    model.total_exposure_constraint = pyo.Constraint(model.L, rule=total_exposure_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    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("\nLoan amounts disbursed:")
        for i in model.L:
            amount_val = pyo.value(model.amount[i])
            if amount_val > 1e-6:  # Only print non-zero values
                print(f"Loan {i}: {amount_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

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