#!/usr/bin/env python3
"""
DOCPLEX implementation for Twitter Reach Optimization Problem
"""

from docplex.mp.model import Model

def twitter_reach_optimization(max_total_tweets_allowed):
    """Optimize tweet selection to maximize reach while respecting constraints."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="twitter_reach_optimization")
    
    # Data from the problem
    user_ids = [1, 2, 3]
    followers = [1500, 2500, 1000]
    max_tweets_per_user = [3, 5, 2]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(user_ids) == len(followers) == len(max_tweets_per_user), "Array length mismatch"
    safe_range = range(min(len(user_ids), len(followers), len(max_tweets_per_user)))  # Safe indexing
    
    # 2. VARIABLES
    # Binary decision variables: x_i = 1 if user i is selected, 0 otherwise
    x = {i: mdl.binary_var(name=f"x_{user_ids[i]}") for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total reach: sum of followers of selected users
    objective = mdl.sum(followers[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Total Tweet Constraint: sum of tweets across selected users <= max_total_tweets_allowed
    total_tweets = mdl.sum(max_tweets_per_user[i] * x[i] for i in safe_range)
    mdl.add_constraint(total_tweets <= max_total_tweets_allowed, ctname="total_tweet_limit")
    
    # User Tweet Constraint: each selected user cannot post more than their individual limit
    # This is inherently handled by the binary nature of x_i and the total tweet constraint
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(x[i])
            if value > 0:
                print(f"User {user_ids[i]} is selected (Followers: {followers[i]}, Max Tweets: {max_tweets_per_user[i]})")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Example usage
if __name__ == "__main__":
    # Assume a maximum total tweets allowed of 6 for this example
    max_total_tweets_allowed = 6
    twitter_reach_optimization(max_total_tweets_allowed)