#!/usr/bin/env python3
"""
DOCplex implementation for election_representative optimization problem
"""

from docplex.mp.model import Model

def election_representative_optimization():
    """Optimize campaign resource allocation to maximize seats won"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="election_representative")
    
    # Data from the problem description
    seats = [1, 2, 3]  # From election.Seats
    min_resource = 1000  # Minimum resource allocation per representative
    total_budget = 1000000  # Total budget constraint
    state_limits = [50000, 60000, 70000]  # From state_resource_limits.Maximum_Resource_Allocation
    
    # CRITICAL: Validate array lengths to prevent IndexError
    n_reps = len(seats)
    assert len(state_limits) == n_reps, "Array length mismatch"
    safe_range = range(min(len(seats), len(state_limits)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables: amount of resources allocated to each representative
    x = {i: mdl.continuous_var(name=f"x_{i}", lb=min_resource) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total seats won: sum(seats[i] * x[i])
    objective = mdl.sum(seats[i] * x[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Total budget constraint: sum(x[i]) <= total_budget
    total_usage = mdl.sum(x[i] for i in safe_range)
    mdl.add_constraint(total_usage <= total_budget, ctname="total_budget")
    
    # State resource limits: x[i] <= state_limits[i]
    for i in safe_range:
        mdl.add_constraint(x[i] <= state_limits[i], ctname=f"state_limit_{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:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

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