# Complete DOCPLEX implementation

from docplex.mp.model import Model

def optimize_race_track():
    """Optimize the number of races at each track to maximize seating capacity utilization."""
    
    # 1. MODEL & DATA SETUP
    mdl = Model(name="race_track_optimization")
    
    # Data from the database
    seating_capacities = [5000, 10000, 15000]
    max_races = [10, 12, 15]
    total_seating_capacity = 300000  # Assuming a total seating capacity of 300,000
    
    # CRITICAL: Validate array lengths to prevent IndexError
    assert len(seating_capacities) == len(max_races), "Array length mismatch"
    safe_range = range(min(len(seating_capacities), len(max_races)))  # Safe indexing
    
    # 2. VARIABLES
    # Decision variables: 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 total seating capacity utilization
    objective = mdl.sum(seating_capacities[i] * races[i] for i in safe_range)
    mdl.maximize(objective)
    
    # 4. CONSTRAINTS
    
    # Constraint 1: Race Limit per Track
    for i in safe_range:
        mdl.add_constraint(races[i] <= max_races[i], ctname=f"race_limit_{i}")
    
    # Constraint 2: Total Seating Capacity
    total_utilization = mdl.sum(seating_capacities[i] * races[i] for i in safe_range)
    mdl.add_constraint(total_utilization <= total_seating_capacity, ctname="total_seating_capacity")
    
    # 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])
            print(f"Races at track {i+1}: {value}")
    else:
        print("No solution found")
        print(f"Status: {mdl.solve_details.status}")
    
    return mdl

# Execute the optimization
optimize_race_track()