import time
import sys
import os
from sqlalchemy import create_engine
from sqlalchemy.exc import OperationalError

def wait_for_db(max_retries=30, retry_delay=2):
    """Wait for database to be ready"""
    
    mysql_host = os.getenv('MYSQL_HOST', 'db')
    mysql_user = os.getenv('MYSQL_USER', 'vendinguser')
    mysql_password = os.getenv('MYSQL_PASSWORD', 'vendingpass')
    mysql_db = os.getenv('MYSQL_DATABASE', 'vending')
    
    db_uri = f'mysql+pymysql://{mysql_user}:{mysql_password}@{mysql_host}:3306/{mysql_db}'
    
    print(f"⏳ Waiting for MySQL at {mysql_host}:3306...")
    
    for attempt in range(1, max_retries + 1):
        try:
            engine = create_engine(db_uri)
            connection = engine.connect()
            connection.close()
            print("✓ MySQL is ready!")
            return True
        except OperationalError as e:
            if attempt < max_retries:
                print(f"Waiting for MySQL... (attempt {attempt}/{max_retries})")
                time.sleep(retry_delay)
            else:
                print(f"❌ Failed to connect to MySQL after {max_retries} attempts")
                print(f"Error: {e}")
                sys.exit(1)
    
    return False

if __name__ == '__main__':
    wait_for_db()