#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Entrepreneur Investment Optimization
"""

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

def optimize_investment():
    """Optimize investment allocation across entrepreneurs to maximize return"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Realistic data for entrepreneurs
    entrepreneurs_data = {
        1: {'return_rate': 0.12},
        2: {'return_rate': 0.18},
        3: {'return_rate': 0.1}
    }
    
    # Business configuration parameters
    total_budget = 1000000  # $1,000,000
    max_individual_investment = 200000  # $200,000
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=entrepreneurs_data.keys())  # Set of entrepreneurs
    
    # 4. PARAMETERS (data containers)
    model.return_rate = pyo.Param(model.I, initialize={i: entrepreneurs_data[i]['return_rate'] for i in model.I})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals, bounds=(0, max_individual_investment))
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.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_rule(model):
        return sum(model.x[i] for i in model.I) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_rule)
    
    # Individual Investment Limit (already handled by variable bounds)
    
    # 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("\nInvestment allocations:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 1e-6:  # Only print non-zero values
                print(f"Entrepreneur {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

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