# Complete PYOMO implementation

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

def election_optimization():
    """Election resource allocation optimization using Pyomo"""
    
    # 1. MODEL CREATION
    model = pyo.ConcreteModel()
    
    # 2. DATA SETUP
    counties = [1, 2, 3]
    votes_coefficients = {1: 0.6, 2: 1.5, 3: 0.9}
    min_allocation = {1: 500, 2: 1000, 3: 600}
    max_allocation = {1: 1000, 2: 2000, 3: 1200}
    total_budget = 3000
    
    # CRITICAL: Validate array lengths before indexing
    assert len(votes_coefficients) == len(min_allocation) == len(max_allocation) == len(counties), "Array length mismatch"
    
    # 3. SETS (Pyomo way to define indices)
    model.I = pyo.Set(initialize=counties)
    
    # 4. PARAMETERS (data containers)
    model.votes_coefficient = pyo.Param(model.I, initialize=votes_coefficients)
    model.min_allocation = pyo.Param(model.I, initialize=min_allocation)
    model.max_allocation = pyo.Param(model.I, initialize=max_allocation)
    
    # 5. VARIABLES
    model.resource_allocation = pyo.Var(model.I, within=pyo.NonNegativeReals)
    
    # 6. OBJECTIVE FUNCTION
    def obj_rule(model):
        return sum(model.votes_coefficient[i] * model.resource_allocation[i] for i in model.I)
    model.objective = pyo.Objective(rule=obj_rule, sense=pyo.maximize)
    
    # 7. CONSTRAINTS
    
    # Total budget constraint
    def budget_constraint_rule(model):
        return sum(model.resource_allocation[i] for i in model.I) <= total_budget
    model.budget_constraint = pyo.Constraint(rule=budget_constraint_rule)
    
    # Minimum and maximum allocation constraints
    def min_allocation_rule(model, i):
        return model.resource_allocation[i] >= model.min_allocation[i]
    model.min_allocation_constraint = pyo.Constraint(model.I, rule=min_allocation_rule)
    
    def max_allocation_rule(model, i):
        return model.resource_allocation[i] <= model.max_allocation[i]
    model.max_allocation_constraint = pyo.Constraint(model.I, rule=max_allocation_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):.3f}")
        
        # Extract variable values
        print("\nResource allocation:")
        for i in model.I:
            allocation_val = pyo.value(model.resource_allocation[i])
            print(f"County {i}: {allocation_val:.3f}")
        
    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
election_optimization()