from twilio.rest import Client
from app.config import Config
import logging
from app import create_app, mysql
from flask import session

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

def test_twilio_setup():
    # Create Flask app and context
    app = create_app()
    with app.app_context():
        # Get Twilio credentials from your database
        cursor = mysql.connection.cursor()
        cursor.execute("""
            SELECT twilio_account_sid, twilio_auth_token, twilio_phone_number
            FROM company_settings
            WHERE company_id = %s
        """, ('bc440145-6657-4fd7-a53b-c3b27c3d0262',))
        settings = cursor.fetchone()
        cursor.close()
        if not settings:
            logger.error("No Twilio settings found in database")
            return False
        print(f"settings: {settings}")

        try:
            # Initialize Twilio client
            client = Client(settings[0], settings[1])
            
            # Test credentials by getting account info
            account = client.api.accounts(settings[0]).fetch()
            logger.info(f"Successfully connected to Twilio account: {account.friendly_name}")
            
            # Make a test call
            test_number = "+923161164417"  # Replace with your number
            logger.info(f"Attempting to call: {test_number}")
            
            call = client.calls.create(
                to=test_number,
                from_=settings[2],
                url=f"{Config.BASE_URL}company/call-campaign/webhook"
            )
            
            logger.info(f"Test call initiated! Call SID: {call.sid}")
            return True
            
        except Exception as e:
            logger.error(f"Error testing Twilio setup: {str(e)}")
            return False

if __name__ == "__main__":
    test_twilio_setup()
