#!/usr/bin/env python3
"""
Gurobipy 12.0.2 Implementation for Election Resource Allocation Problem
"""

import gurobipy as gp
from gurobipy import GRB

def election_resource_allocation():
    """Optimize resource allocation for election campaign to maximize voter turnout."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("election_resource_allocation")
    
    # Data from the problem
    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 loops
    assert len(counties) == len(turnout_per_dollar) == len(population), "Array length mismatch"
    
    # 2. VARIABLES
    x = {i: model.addVar(vtype=GRB.CONTINUOUS, name=f"x_{i}", lb=0) for i in counties}
    
    # 3. OBJECTIVE FUNCTION
    model.setObjective(gp.quicksum(turnout_per_dollar[i] * x[i] for i in counties), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS
    
    # Total Budget Constraint
    model.addConstr(gp.quicksum(x[i] for i in counties) <= total_budget, name="total_budget")
    
    # Minimum Allocation Constraint
    for i in counties:
        model.addConstr(x[i] >= min_allocation, name=f"min_allocation_{i}")
    
    # Maximum Allocation Constraint
    for i in counties:
        model.addConstr(x[i] <= max_allocation, name=f"max_allocation_{i}")
    
    # Population Proportionality Constraint
    for i in counties:
        model.addConstr(x[i] >= proportionality_factor * population[i], name=f"proportionality_{i}")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in counties:
            print(f"x[{i}] = {x[i].x:.3f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

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