#!/usr/bin/env python3
"""
Gurobipy 12.0.2 Implementation for University Basketball Team Selection
"""

import gurobipy as gp
from gurobipy import GRB

def optimize_basketball_teams():
    """Optimize the selection of basketball teams for a tournament."""
    
    # 1. MODEL & DATA SETUP
    model = gp.Model("university_basketball")
    
    # Data from the database
    team_ids = [1, 2, 3, 4, 5]
    win_percent = {1: 85.0, 2: 78.5, 3: 72.0, 4: 80.5, 5: 75.0}
    conference_indicator = {1: 'East', 2: 'West', 3: 'South', 4: 'East', 5: 'West'}
    location_indicator = {1: 'New York', 2: 'Los Angeles', 3: 'Chicago', 4: 'New York', 5: 'Los Angeles'}
    
    # Business configuration
    total_teams = 3
    min_east = 1
    min_west = 1
    min_south = 1
    max_ny = 1
    max_la = 1
    max_chicago = 1
    
    # CRITICAL: Validate array lengths before loops
    assert len(team_ids) == len(win_percent) == len(conference_indicator) == len(location_indicator), "Array length mismatch"
    
    # 2. VARIABLES
    x = {i: model.addVar(vtype=GRB.BINARY, name=f"x_{i}") for i in team_ids}
    
    # 3. OBJECTIVE FUNCTION
    model.setObjective(gp.quicksum(win_percent[i] * x[i] for i in team_ids), GRB.MAXIMIZE)
    
    # 4. CONSTRAINTS
    
    # Total Teams Selected
    model.addConstr(gp.quicksum(x[i] for i in team_ids) == total_teams, name="total_teams")
    
    # East Conference Diversity
    model.addConstr(gp.quicksum(x[i] for i in team_ids if conference_indicator[i] == 'East') >= min_east, name="min_east")
    
    # West Conference Diversity
    model.addConstr(gp.quicksum(x[i] for i in team_ids if conference_indicator[i] == 'West') >= min_west, name="min_west")
    
    # South Conference Diversity
    model.addConstr(gp.quicksum(x[i] for i in team_ids if conference_indicator[i] == 'South') >= min_south, name="min_south")
    
    # New York Geographical Limit
    model.addConstr(gp.quicksum(x[i] for i in team_ids if location_indicator[i] == 'New York') <= max_ny, name="max_ny")
    
    # Los Angeles Geographical Limit
    model.addConstr(gp.quicksum(x[i] for i in team_ids if location_indicator[i] == 'Los Angeles') <= max_la, name="max_la")
    
    # Chicago Geographical Limit
    model.addConstr(gp.quicksum(x[i] for i in team_ids if location_indicator[i] == 'Chicago') <= max_chicago, name="max_chicago")
    
    # 5. SOLVING & RESULTS
    model.optimize()
    
    if model.status == GRB.OPTIMAL:
        print(f"Optimal value: {model.objVal}")
        for i in team_ids:
            if x[i].x > 1e-6:
                print(f"Team {i} selected: {x[i].x:.0f}")
    elif model.status == GRB.INFEASIBLE:
        print("Problem is infeasible")
    elif model.status == GRB.UNBOUNDED:
        print("Problem is unbounded")
    
    return model

# Execute the optimization
optimize_basketball_teams()