#!/usr/bin/env python3
"""
Pyomo 6.9.2 Implementation for Election Resource Allocation Problem
"""

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

def election_resource_allocation():
    """Optimize resource allocation for election campaign to maximize voter turnout."""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    counties = [1, 2, 3]
    turnout_per_dollar = {1: 0.55, 2: 0.65, 3: 0.45}
    population = {1: 15000, 2: 25000, 3: 10000}
    total_budget = 1000000
    min_allocation = 10000
    max_allocation = 100000
    proportionality_factor = 0.01
    
    # CRITICAL: Validate array lengths before indexing
    assert len(turnout_per_dollar) == len(population) == len(counties), "Array length mismatch"
    
    # 3. SETS
    model.I = pyo.Set(initialize=counties)
    
    # 4. PARAMETERS
    model.turnout_per_dollar = pyo.Param(model.I, initialize=turnout_per_dollar)
    model.population = pyo.Param(model.I, initialize=population)
    
    # 5. VARIABLES
    model.x = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.turnout_per_dollar[i] * model.x[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total Budget Constraint
    def total_budget_rule(model):
        return sum(model.x[i] for i in model.I) <= total_budget
    model.total_budget_constraint = pyo.Constraint(rule=total_budget_rule)
    
    # Minimum Allocation Constraint
    def min_allocation_rule(model, i):
        return model.x[i] >= min_allocation
    model.min_allocation_constraint = pyo.Constraint(model.I, rule=min_allocation_rule)
    
    # Maximum Allocation Constraint
    def max_allocation_rule(model, i):
        return model.x[i] <= max_allocation
    model.max_allocation_constraint = pyo.Constraint(model.I, rule=max_allocation_rule)
    
    # Population Proportionality Constraint
    def population_proportionality_rule(model, i):
        return model.x[i] >= proportionality_factor * model.population[i]
    model.population_proportionality_constraint = pyo.Constraint(model.I, rule=population_proportionality_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("\nResource Allocation:")
        for i in model.I:
            x_val = pyo.value(model.x[i])
            print(f"County {i}: ${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

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