#!/usr/bin/env python3
"""
DOCplex implementation for maximizing trust-weighted ratings of reviews
"""

from docplex.mp.model import Model

def optimize_trust_weights():
    """Optimize trust weights to maximize trust-weighted ratings"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="epinions_1")
    
    # Data from the problem statement
    ratings = [4.5, 3.8, 5.0, 3.0, 4.0]  # Coefficients for objective function
    trust_levels = [0.6, 0.8, 1.0, 0.7, 0.7]  # Upper bounds for trust weights
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(ratings) == len(trust_levels), "Array length mismatch"
    safe_range = range(min(len(ratings), len(trust_levels)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables: trust weights for each review
    w = {i: mdl.continuous_var(name=f"w_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the sum of trust-weighted ratings
    objective = mdl.sum(ratings[i] * w[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    # Non-negative trust weights (already handled by lb=0 in variable definition)
    
    # Trust weight upper bound
    for i in safe_range:
        mdl.add_constraint(w[i] <= trust_levels[i], ctname=f"trust_bound_{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(w[i])
            print(f"w[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization
if __name__ == "__main__":
    optimize_trust_weights()