# Complete PYOMO implementation

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

def optimize_tweet_reach():
    """Optimize tweet reach by selecting users to maximize followers while respecting tweet limits."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # User data: user_id, followers, max_tweets_per_user
    user_data = {
        1: {'followers': 1500, 'max_tweets': 3},
        2: {'followers': 2500, 'max_tweets': 5},
        3: {'followers': 1000, 'max_tweets': 2}
    }
    
    # Business configuration parameter
    max_total_tweets_allowed = 6  # Example value, adjust as needed
    
    # Validate data consistency
    assert len(user_data) > 0, "User data must not be empty"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=user_data.keys())  # Set of users
    
    # 4. PARAMETERS (data containers)
    model.followers = pyo.Param(model.I, initialize={i: user_data[i]['followers'] for i in model.I})
    model.max_tweets_per_user = pyo.Param(model.I, initialize={i: user_data[i]['max_tweets'] for i in model.I})
    
    # 5. VARIABLES
    # Binary decision variable: x_i = 1 if user i is selected, 0 otherwise
    model.x = pyo.Var(model.I, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    # Maximize total reach (sum of followers of selected users)
    def obj_rule(model):
        return sum(model.followers[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total Tweet Constraint: Sum of tweets across selected users <= max_total_tweets_allowed
    def total_tweet_rule(model):
        return sum(model.max_tweets_per_user[i] * model.x[i] for i in model.I) <= max_total_tweets_allowed
    model.total_tweet_constraint = pyo.Constraint(rule=total_tweet_rule)
    
    # User Tweet Constraint: Each selected user cannot post more than their individual limit
    # This is inherently handled by the binary variable x_i and the max_tweets_per_user parameter
    
    # 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(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nSelected users:")
        for i in model.I:
            if pyo.value(model.x[i]) > 0.5:  # Only print selected users
                print(f"User {i} is selected with {user_data[i]['followers']} followers.")
        
    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_tweet_reach()