#!/usr/bin/env python3
"""
Gurobipy Implementation for Race Track Optimization Problem
"""

import gurobipy as gp
from gurobipy import GRB

def optimize_race_track():
    """Optimize the number of races at each track to maximize seating capacity utilization."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("race_track_optimization")
    
    # Data from the database
    seating_capacities = [5000, 10000, 15000]
    max_races = [10, 12, 15]
    total_seating_capacity = 300000  # Assuming a total available seating capacity
    
    # Number of tracks
    n_tracks = len(seating_capacities)
    
    # CRITICAL: Validate array lengths before loops
    assert len(seating_capacities) == len(max_races) == n_tracks, "Array length mismatch"
    
    # 2. VARIABLES
    # Decision variables: number of races at each track
    x = {i: model.addVar(vtype=GRB.INTEGER, name=f"x_{i}", lb=0) for i in range(n_tracks)}
    
    # 3. OBJECTIVE FUNCTION
    # Maximize total seating capacity utilization
    model.setObjective(gp.quicksum(seating_capacities[i] * x[i] for i in range(n_tracks)), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS
    
    # Constraint 1: Race Limit per Track
    for i in range(n_tracks):
        model.addConstr(x[i] <= max_races[i], name=f"race_limit_{i}")
    
    # Constraint 2: Total Seating Capacity
    model.addConstr(gp.quicksum(seating_capacities[i] * x[i] for i in range(n_tracks)) <= total_seating_capacity, name="total_seating_capacity")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in range(n_tracks):
            print(f"Races at track {i}: {x[i].x}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Execute the optimization
optimize_race_track()