# Complete PYOMO implementation

import pyomo.environ as pyo
from pyomo.opt import SolverFactory

def epinions_optimization():
    """Optimization model to maximize trust-weighted ratings of reviews."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    # Ratings from the review table
    ratings = [4.5, 3.8, 5.0, 3.0, 4.0]
    
    # Trust levels from the trust table
    trust_levels = [0.6, 0.8, 1.0, 0.7, 0.7]
    
    # Number of reviews
    n_reviews = len(ratings)
    
    # CRITICAL: Validate array lengths before indexing
    assert len(ratings) == len(trust_levels) == n_reviews, "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.RangeSet(1, n_reviews)  # 1-based indexing
    
    # 4. PARAMETERS (data containers)
    model.rating = pyo.Param(model.I, initialize={i+1: ratings[i] for i in range(n_reviews)})
    model.trust = pyo.Param(model.I, initialize={i+1: trust_levels[i] for i in range(n_reviews)})
    
    # 5. VARIABLES
    # Trust weights for each review
    model.w = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    # Maximize the sum of trust-weighted ratings
    def obj_rule(model):
        return sum(model.rating[i] * model.w[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Non-Negative Trust Weights
    def non_negative_rule(model, i):
        return model.w[i] >= 0
    model.non_negative_constraint = pyo.Constraint(model.I, rule=non_negative_rule)
    
    # Trust Weight Upper Bound
    def trust_bound_rule(model, i):
        return model.w[i] <= model.trust[i]
    model.trust_bound_constraint = pyo.Constraint(model.I, rule=trust_bound_rule)
    
    # 8. SOLVING WITH GUROBI (your available solver)
    solver = SolverFactory('gurobi')
    
    # Optional: Set solver options
    solver.options['TimeLimit'] = 300  # 5 minutes
    solver.options['MIPGap'] = 0.01    # 1% gap
    
    # Solve the model
    results = solver.solve(model, tee=True)  # tee=True shows solver output
    
    # 9. RESULT PROCESSING
    # Check solver status
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nTrust weights:")
        for i in model.I:
            w_val = pyo.value(model.w[i])
            print(f"w[{i}] = {w_val:.3f}")
        
    elif results.solver.termination_condition == pyo.TerminationCondition.infeasible:
        print("Problem is infeasible")
    elif results.solver.termination_condition == pyo.TerminationCondition.unbounded:
        print("Problem is unbounded")
    else:
        print(f"Solver terminated with condition: {results.solver.termination_condition}")
    
    return model

# Run the optimization
if __name__ == "__main__":
    epinions_optimization()