#!/usr/bin/env python3
"""
DOCPLEX Implementation for Election Campaign Resource Allocation
"""

from docplex.mp.model import Model

def election_campaign_optimization():
    """Optimize resource allocation for election campaign to maximize voter turnout."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="election_campaign_optimization")
    
    # Data from the problem statement
    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 to prevent IndexError
    assert len(counties) == len(turnout_per_dollar) == len(population), "Array length mismatch"
    safe_range = range(min(len(counties), len(turnout_per_dollar), len(population)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables: x_i = amount allocated to county i
    x = {i: mdl.continuous_var(name=f"x_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total expected voter turnout
    objective = mdl.sum(turnout_per_dollar[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Total Budget Constraint
    total_allocation = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_allocation <= total_budget, ctname="total_budget")
    
    # Minimum Allocation Constraint
    for i in safe_range:
        mdl.add_constraint(x[i] >= min_allocation, ctname=f"min_allocation_{i}")
    
    # Maximum Allocation Constraint
    for i in safe_range:
        mdl.add_constraint(x[i] <= max_allocation, ctname=f"max_allocation_{i}")
    
    # Population Proportionality Constraint
    for i in safe_range:
        mdl.add_constraint(x[i] >= proportionality_factor * population[i], ctname=f"proportionality_{i}")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(x[i])
            print(f"x[{i}] = {value:.2f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

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