# Complete PYOMO implementation - Retry Attempt 1

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

def decoration_competition_optimization():
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    members = [1, 2, 3]
    rounds = [1, 2, 3]
    
    # Ranking points data
    rank_in_round_data = {
        (1, 1): 15,
        (2, 2): 20,
        (3, 3): 25
    }
    
    # Validate data consistency
    assert len(members) == 3, "Members data length mismatch"
    assert len(rounds) == 3, "Rounds data length mismatch"
    assert len(rank_in_round_data) == 3, "Rank_in_Round data length mismatch"
    
    # 3. SETS
    model.Members = pyo.Set(initialize=members)
    model.Rounds = pyo.Set(initialize=rounds)
    
    # 4. PARAMETERS
    model.Rank_in_Round = pyo.Param(model.Members, model.Rounds, initialize=rank_in_round_data, default=0)
    
    # 5. VARIABLES
    model.Assignment = pyo.Var(model.Members, model.Rounds, within=pyo.Binary)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.Rank_in_Round[m, r] * model.Assignment[m, r] for m in model.Members for r in model.Rounds)
    model.Objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Member Participation Limit
    def member_limit_rule(model, m):
        return sum(model.Assignment[m, r] for r in model.Rounds) <= 2
    model.MemberLimit = pyo.Constraint(model.Members, rule=member_limit_rule)
    
    # Round Participant Requirement
    def round_requirement_rule(model, r):
        return sum(model.Assignment[m, r] for m in model.Members) == 2
    model.RoundRequirement = pyo.Constraint(model.Rounds, rule=round_requirement_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
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print(f"Optimal value: {pyo.value(model.Objective)}")
        
        # Extract assignment values
        print("\nAssignment values:")
        for m in model.Members:
            for r in model.Rounds:
                if pyo.value(model.Assignment[m, r]) > 0.5:
                    print(f"Member {m} assigned to Round {r}")
                    
    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__":
    decoration_competition_optimization()