#!/usr/bin/env python3
"""
DOCplex 2.29.245 Implementation for Voter Resource Allocation Problem
"""

from docplex.mp.model import Model

def voter_resource_allocation():
    """Optimize resource allocation to maximize expected votes."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="voter_resource_allocation")
    
    # Data from the problem
    majors = ['Computer Science', 'Biology', 'History']
    expected_votes = [150, 100, 80]
    number_of_students = [200, 150, 100]
    
    # Business configuration
    total_budget = 50000
    min_allocation = 500
    max_allocation = 5000
    units_per_student = 10
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(majors) == len(expected_votes) == len(number_of_students), "Array length mismatch"
    safe_range = range(min(len(majors), len(expected_votes), len(number_of_students)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables: resource allocation per major
    x = {i: mdl.integer_var(name=f"x_{majors[i]}", lb=min_allocation, ub=max_allocation) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total expected votes
    objective = mdl.sum(expected_votes[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Total Budget Constraint
    total_usage = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_usage <= total_budget, ctname="total_budget")
    
    # Proportional Resource Allocation Constraint
    for i in safe_range:
        mdl.add_constraint(x[i] <= units_per_student * number_of_students[i], ctname=f"proportional_{majors[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"Resource allocation for {majors[i]}: {value}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

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