#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Voter Optimization Problem
"""

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

def voter_optimization():
    """Optimize promotional budget allocation to maximize votes."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    contestants = [1, 2, 3]
    states = ['CA', 'TX', 'NY']
    total_budget = 150000
    max_state_budget = 25000
    conversion_rate = 0.6
    
    # 3. SETS
    model.contestants = pyo.Set(initialize=contestants)
    model.states = pyo.Set(initialize=states)
    
    # 4. VARIABLES
    model.x = pyo.Var(model.contestants, model.states, within=pyo.NonNegativeReals, bounds=(0, max_state_budget))
    
    # 5. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(conversion_rate * model.x[i, j] for i in model.contestants for j in model.states)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 6. CONSTRAINTS
    
    # Total Budget Constraint
    def total_budget_rule(model):
        return sum(model.x[i, j] for i in model.contestants for j in model.states) <= total_budget
    model.total_budget_constraint = pyo.Constraint(rule=total_budget_rule)
    
    # State-Level Budget Constraint
    def state_budget_rule(model, i, j):
        return model.x[i, j] <= max_state_budget
    model.state_budget_constraint = pyo.Constraint(model.contestants, model.states, rule=state_budget_rule)
    
    # 7. 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
    
    # 8. 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("\nPromotional Budget Allocation:")
        for i in model.contestants:
            for j in model.states:
                x_val = pyo.value(model.x[i, j])
                if x_val > 1e-6:  # Only print non-zero values
                    print(f"Contestant {i}, State {j}: {x_val:.2f}")
        
    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

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