# Complete DOCPLEX implementation

from docplex.mp.model import Model

def election_representative_optimization(total_campaign_resources):
    """Optimize the allocation of campaign resources to maximize seats won."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="election_representative")
    
    # Data from the database
    seats = [1, 2, 3]
    min_effort = [10.0, 15.0, 20.0]
    max_effort = [50.0, 60.0, 70.0]
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(seats) == len(min_effort) == len(max_effort), "Array length mismatch"
    safe_range = range(min(len(seats), len(min_effort), len(max_effort)))  # Safe indexing
    
    # 2. VARIABLES
    # Variable dictionaries (most common)
    effort = {i: mdl.continuous_var(name=f"effort_{i}", lb=min_effort[i], ub=max_effort[i]) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total number of seats won
    objective = mdl.sum(seats[i] * effort[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total effort constraint
    total_effort = mdl.sum(effort[i] for i in safe_range)
    mdl.add_constraint(total_effort <= total_campaign_resources, ctname="total_effort_limit")
    
    # 5. SOLVING & RESULTS
    solution = mdl.solve()
    
    if solution:
        print(f"Optimal value: {solution.objective_value}")
        for i in safe_range:
            value = solution.get_value(effort[i])
            if value > 1e-6:
                print(f"effort[{i}] = {value:.3f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Example usage
total_campaign_resources = 100.0  # Example total campaign resources
election_representative_optimization(total_campaign_resources)