# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_race_track():
    """Optimize the number of races to maximize spectators"""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="race_track_optimization")
    
    # Data from the problem statement
    seating = [5000, 10000, 15000]
    max_spectators = [4500, 9500, 14500]
    total_races_limit = 10
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(seating) == len(max_spectators), "Array length mismatch"
    safe_range = range(min(len(seating), len(max_spectators)))  # Safe indexing
    
    # 2. VARIABLES
    # Integer variables for the number of races at each track
    races = {i: mdl.integer_var(name=f"races_{i}", lb=0) for i in safe_range}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize the total number of spectators
    objective = mdl.sum(seating[i] * races[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS - CORRECT SYNTAX PATTERNS
    
    # Total number of races constraint
    total_races = mdl.sum(races[i] for i in safe_range)
    mdl.add_constraint(total_races <= total_races_limit, ctname="total_races_limit")
    
    # Spectator capacity constraints for each track
    for i in safe_range:
        mdl.add_constraint(seating[i] * races[i] <= max_spectators[i], ctname=f"capacity_{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(races[i])
            if value > 1e-6:
                print(f"races[{i}] = {value:.0f}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Run the optimization
optimize_race_track()