# Complete PYOMO implementation

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

def voting_optimization():
    """Optimize the distribution of votes among contestants"""

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

    # 2. DATA SETUP
    # Example data for demonstration purposes
    contestants = [1, 2, 3]
    states = [1, 2, 3]
    max_votes = {1: 300, 2: 295, 3: 305}  # Maximum votes per contestant
    min_votes = {(1, 1): 50, (1, 2): 40, (1, 3): 60,
                 (2, 1): 45, (2, 2): 55, (2, 3): 50,
                 (3, 1): 40, (3, 2): 50, (3, 3): 55}  # Minimum votes per state

    # 3. SETS
    model.I = pyo.Set(initialize=contestants)
    model.J = pyo.Set(initialize=states)

    # 4. PARAMETERS
    model.MaxVotes = pyo.Param(model.I, initialize=max_votes)
    model.MinVotes = pyo.Param(model.I, model.J, initialize=min_votes)

    # 5. VARIABLES
    model.x = pyo.Var(model.I, model.J, within=pyo.NonNegativeIntegers)

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

    # 7. CONSTRAINTS
    # Maximum Votes per Contestant
    def max_votes_rule(model, i):
        return sum(model.x[i, j] for j in model.J) <= model.MaxVotes[i]
    model.max_votes_constraint = pyo.Constraint(model.I, rule=max_votes_rule)

    # Minimum Votes per State
    def min_votes_rule(model, i, j):
        return model.x[i, j] >= model.MinVotes[i, j]
    model.min_votes_constraint = pyo.Constraint(model.I, model.J, rule=min_votes_rule)

    # 8. SOLVING WITH GUROBI
    solver = SolverFactory('gurobi')

    # Solve the model
    results = solver.solve(model, tee=True)

    # 9. RESULT PROCESSING
    if results.solver.termination_condition == pyo.TerminationCondition.optimal:
        print("Optimal solution found!")
        print(f"Optimal value: {pyo.value(model.objective)}")

        # Extract variable values
        print("\nVariable values:")
        for i in model.I:
            for j in model.J:
                x_val = pyo.value(model.x[i, j])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"x[{i},{j}] = {x_val}")

    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
voting_optimization()