#!/usr/bin/env python3
"""
Gurobipy 12.0.2 Implementation for Twitter Reach Optimization Problem
"""

import gurobipy as gp
from gurobipy import GRB

def optimize_twitter_reach(max_total_tweets_allowed):
    """Optimize the reach of tweets by selecting users strategically."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("twitter_reach_optimization")
    
    # Data from the problem
    user_ids = [1, 2, 3]
    followers = {1: 1500, 2: 2500, 3: 1000}
    max_tweets_per_user = {1: 3, 2: 5, 3: 2}
    
    # CRITICAL: Validate array lengths before loops
    assert len(user_ids) == len(followers) == len(max_tweets_per_user), "Array length mismatch"
    
    # 2. VARIABLES
    # Binary decision variables indicating whether a user is selected to tweet
    x = {i: model.addVar(vtype=GRB.BINARY, name=f"x_{i}") for i in user_ids}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total reach of the tweets
    model.setObjective(gp.quicksum(followers[i] * x[i] for i in user_ids), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS
    
    # Total Tweet Constraint: The total number of tweets across all selected users cannot exceed the maximum total tweets allowed
    model.addConstr(gp.quicksum(max_tweets_per_user[i] * x[i] for i in user_ids) <= max_total_tweets_allowed, name="total_tweet_limit")
    
    # User Tweet Constraint: Each selected user cannot post more tweets than their individual maximum limit
    # This is inherently handled by the binary nature of x_i and the max_tweets_per_user in the total tweet constraint
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in user_ids:
            if x[i].x > 1e-6:
                print(f"User {i} is selected to tweet.")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Example usage
if __name__ == "__main__":
    # Assume the maximum total tweets allowed is 6
    max_total_tweets_allowed = 6
    optimize_twitter_reach(max_total_tweets_allowed)