# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_reviews():
    """Optimize the selection of user reviews to maximize trust score."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="epinions_1")
    
    # Data: Trust scores and ratings for each review
    trust_scores = [0.7, 0.9, 0.4, 0.3, 0.1]
    ratings = [5, 2, 4, 3, 1]
    max_reviews = 3
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(trust_scores) == len(ratings), "Array length mismatch"
    safe_range = range(len(trust_scores))  # Safe indexing
    
    # 2. VARIABLES
    # Binary decision variables for each review
    x = {i: mdl.binary_var(name=f"x_{i}") for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the overall trust score
    objective = mdl.sum(trust_scores[i] * ratings[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    # Constraint: Total number of selected reviews must not exceed max_reviews
    total_selected = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_selected <= max_reviews, ctname="max_reviews")
    
    # 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[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")

    return mdl

# Run the optimization
optimize_reviews()