# Complete PYOMO implementation

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

def decoration_competition_optimization():
    """Optimization for decoration competition"""

    # 1. MODEL CREATION
    model = pyo.ConcreteModel()

    # 2. DATA SETUP
    # Example data based on the provided schema and realistic data
    rounds = [1, 2, 3]
    members = [101, 102, 103]
    
    # Rank points data from ObjectiveCoefficients table
    rank_points_data = {
        (1, 101): 25.0,
        (2, 102): 30.0,
        (3, 103): 0.0,
        (1, 102): 20.0,
        (2, 101): 0.0
    }
    
    # 3. SETS
    model.Rounds = pyo.Set(initialize=rounds)
    model.Members = pyo.Set(initialize=members)

    # 4. PARAMETERS
    model.rank_points = pyo.Param(model.Rounds, model.Members, initialize=rank_points_data, default=0.0)

    # 5. VARIABLES
    model.x = pyo.Var(model.Rounds, model.Members, within=pyo.Binary)

    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.rank_points[i, j] * model.x[i, j] for i in model.Rounds for j in model.Members)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)

    # 7. CONSTRAINTS
    # Constraint: Each member can participate in a maximum of three rounds
    def participation_limit_rule(model, j):
        return sum(model.x[i, j] for i in model.Rounds) <= 3
    model.participation_limit = pyo.Constraint(model.Members, rule=participation_limit_rule)

    # 8. SOLVING WITH GUROBI
    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("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")
        
        # Extract variable values
        print("\nParticipation decisions:")
        for i in model.Rounds:
            for j in model.Members:
                x_val = pyo.value(model.x[i, j])
                if x_val > 0.5:  # Only print participation decisions
                    print(f"Member {j} participates in Round {i}")
        
    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
decoration_competition_optimization()