# Complete PYOMO implementation

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

def optimize_promotional_tweets():
    """Optimize the allocation of promotional tweets to maximize engagement."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Example data based on the problem context
    user_ids = [1, 2, 3]
    engagement_coefficients = [0.6, 0.8, 0.4]
    follower_limit = 2
    min_engagement_threshold = 0.5
    
    # CRITICAL: Validate array lengths before indexing
    assert len(user_ids) == len(engagement_coefficients), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=user_ids)
    
    # 4. PARAMETERS
    model.engagement_coefficient = pyo.Param(model.I, initialize={user_ids[i]: engagement_coefficients[i] for i in range(len(user_ids))})
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.engagement_coefficient[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total number of users constraint
    def total_users_rule(model):
        return sum(model.x[i] for i in model.I) <= follower_limit
    model.total_users_constraint = pyo.Constraint(rule=total_users_rule)
    
    # Minimum engagement score constraint
    def min_engagement_rule(model, i):
        return model.x[i] * model.engagement_coefficient[i] >= min_engagement_threshold * model.x[i]
    model.min_engagement_constraint = pyo.Constraint(model.I, rule=min_engagement_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("\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}] = {int(x_val)}")
        
    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_promotional_tweets()