# Complete PYOMO implementation

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

def investment_optimization():
    """Investment optimization using Pyomo"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    entrepreneurs = [1, 2, 3]
    expected_return_rates = {1: 0.12, 2: 0.18, 3: 0.22}
    money_requested = {1: 20000, 2: 25000, 3: 30000}
    total_budget = 60000
    
    # CRITICAL: Validate data lengths before indexing
    assert len(expected_return_rates) == len(money_requested) == len(entrepreneurs), "Data length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=entrepreneurs)
    
    # 4. PARAMETERS
    model.expected_return_rate = pyo.Param(model.I, initialize=expected_return_rates)
    model.money_requested = pyo.Param(model.I, initialize=money_requested)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.expected_return_rate[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total budget constraint
    def budget_constraint_rule(model):
        return sum(model.x[i] for i in model.I) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_constraint_rule)
    
    # Individual investment constraints
    def investment_constraint_rule(model, i):
        return model.x[i] <= model.money_requested[i]
    model.investment_constraints = pyo.Constraint(model.I, rule=investment_constraint_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):.3f}")
        
        # Extract variable values
        print("\nInvestment amounts:")
        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
investment_optimization()