# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_promotional_tweets():
    """Optimize the allocation of promotional tweets to maximize engagement."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="twitter_1")
    
    # Data: User engagement coefficients
    user_ids = [1, 2, 3]
    engagement_coefficients = [0.6, 0.8, 0.4]
    
    # Business configuration parameters
    follower_limit = 2
    min_engagement_threshold = 0.5
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(user_ids) == len(engagement_coefficients), "Array length mismatch"
    safe_range = range(len(user_ids))  # Safe indexing
    
    # 2. VARIABLES
    # Binary decision variables for each user
    x = {i: mdl.binary_var(name=f"x_{user_ids[i]}") for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total engagement score
    objective = mdl.sum(engagement_coefficients[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total number of users constraint
    total_users = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_users <= follower_limit, ctname="follower_limit")
    
    # Minimum engagement score constraint
    for i in safe_range:
        mdl.add_constraint(x[i] * engagement_coefficients[i] >= min_engagement_threshold * x[i], 
                           ctname=f"min_engagement_{user_ids[i]}")
    
    # 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 > 1e-6:
                print(f"x[{user_ids[i]}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_promotional_tweets()