import mysql.connector
import pika
import sys
import json

# Database configuration
DB_CONFIG = {
    'host': '10.0.0.109',
    'port': 3306,
    'database': 'voicebot_cluster',
    'user': 'admin',  # Replace with your MySQL username
    'password': 'mcube@admin123',  # Replace with your MySQL password
}

# RabbitMQ configuration
RABBITMQ_HOST = '10.0.0.109'
RABBITMQ_QUEUE = 'audio_jobs'
RABBITMQ_USER = 'mcube'
RABBITMQ_PASS = 'mcube@0121'
RABBITMQ_VHOST = 'vGadmin'  # Use vGadmin virtual host where mcube has access

def get_unprocessed_calls(bid=None):
    # Connect to MySQL database
    try:
        connection = mysql.connector.connect(**DB_CONFIG)
        cursor = connection.cursor()

        # Use dynamic table name if bid is provided, otherwise use default
        if bid:
            calls_table = f"{bid}_calls"
        else:
            calls_table = "7417_calls"  # Default fallback

        # Fetch unprocessed calls (status = 0) with both callid and bid
        query = f"SELECT callid, bid FROM {calls_table} WHERE status = 0"
        cursor.execute(query)
        calls = cursor.fetchall()

        # Close the database connection
        cursor.close()
        connection.close()

        return calls  # Return list of tuples (callid, bid)
    except mysql.connector.Error as err:
        print(f"Error: {err}")
        sys.exit(1)

def send_to_rabbitmq(calls):
    # Connect to RabbitMQ
    try:
        credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASS)
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(
                host=RABBITMQ_HOST, 
                virtual_host=RABBITMQ_VHOST,
                credentials=credentials
            )
        )
        channel = connection.channel()

        # Declare the queue (if it doesn't exist)
        channel.queue_declare(queue=RABBITMQ_QUEUE, durable=True)

        # Publish each call as JSON message with callid and bid
        for callid, bid in calls:
            message_data = {
                "callid": callid,
                "bid": bid
            }
            message = json.dumps(message_data)
            channel.basic_publish(
                exchange='',
                routing_key=RABBITMQ_QUEUE,
                body=message,
                properties=pika.BasicProperties(
                    delivery_mode=2,  # Make the message persistent
                )
            )
            print(f"➡️ Queued callid: {callid}, bid: {bid}")

        # Close the RabbitMQ connection
        connection.close()
        print("✅ Done queuing unprocessed calls.")
    except pika.exceptions.AMQPConnectionError as err:
        print(f"Error connecting to RabbitMQ: {err}")
        sys.exit(1)

if __name__ == '__main__':
    import sys
    
    # Check if bid is provided as command line argument
    bid = None
    if len(sys.argv) > 1:
        bid = sys.argv[1]
        print(f"📤 Fetching unprocessed calls for business ID: {bid}")
    else:
        print("📤 Fetching unprocessed calls from default table...")
        print("💡 Usage: python rabbit.py <bid> (e.g., python rabbit.py 6840)")
    
    calls = get_unprocessed_calls(bid)
    if calls:
        send_to_rabbitmq(calls)
        print(f"✅ Queued {len(calls)} calls for business: {bid or 'default'}")
    else:
        print(f"No unprocessed calls found for business: {bid or 'default'}")
