# Complete PYOMO implementation

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

def medicine_enzyme_interaction_optimization():
    """Optimize medicine-enzyme interactions for research impact"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    interaction_ids = [1, 2, 3]
    impact_coefficients = [1.5, 0.9, 1.2]
    interaction_costs = [1500, 800, 1200]
    resource_usage = [25, 10, 18]
    total_budget = 3000  # Example budget
    total_resources = 50  # Example resource limit
    
    # CRITICAL: Validate array lengths before indexing
    assert len(interaction_ids) == len(impact_coefficients) == len(interaction_costs) == len(resource_usage), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=interaction_ids)
    
    # 4. PARAMETERS
    model.coefficient = pyo.Param(model.I, initialize={interaction_ids[i]: impact_coefficients[i] for i in range(len(interaction_ids))})
    model.cost = pyo.Param(model.I, initialize={interaction_ids[i]: interaction_costs[i] for i in range(len(interaction_ids))})
    model.resources = pyo.Param(model.I, initialize={interaction_ids[i]: resource_usage[i] for i in range(len(interaction_ids))})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.coefficient[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Budget constraint
    def budget_rule(model):
        return sum(model.cost[i] * model.x[i] for i in model.I) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_rule)
    
    # Resource constraint
    def resource_rule(model):
        return sum(model.resources[i] * model.x[i] for i in model.I) <= total_resources
    model.resource_constraint = pyo.Constraint(rule=resource_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("\nSelected interactions:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            if x_val > 0.5:  # Only print selected interactions
                print(f"Interaction {i} selected")
        
    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
medicine_enzyme_interaction_optimization()