import os
import uuid
from tigerbeetle import Account, ClientSync
import logging

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

# Ensure these are set correctly in your environment or .env file
CLUSTER_ID = int(os.getenv("TB_CLUSTER_ID", "0"))
TB_ADDRESS = os.getenv("TB_ADDRESS", "127.0.0.1:3000")

def test_tigerbeetle_connection():
    client = None
    try:
        logger.info(f"Attempting to connect to TigerBeetle cluster {CLUSTER_ID} at {TB_ADDRESS}...")
        client = ClientSync(CLUSTER_ID, TB_ADDRESS)
        logger.info("Successfully connected to TigerBeetle.")

        # Try to create a dummy account to verify functionality
        test_account_id = uuid.uuid4().int # Use uuid.int for 128-bit ID
        
        account_to_create = Account(
            id=test_account_id,
            ledger=1, # Example ledger
            code=100, # Example code
        )

        logger.info(f"Attempting to create a test account with ID: {test_account_id}...")
        errors = client.create_accounts([account_to_create])

        if errors:
            for error in errors:
                logger.error(f"Error creating test account {error.index}: {error.code.name}")
            return False, f"Failed to create test account: {', '.join([e.code.name for e in errors])}"
        else:
            logger.info("Test account created successfully.")
            return True, "Connection and basic account creation successful."

    except Exception as e:
        logger.error(f"Failed to connect or interact with TigerBeetle: {e}")
        return False, str(e)
    finally:
        if client:
            client.close()
            logger.info("TigerBeetle client closed.")

if __name__ == "__main__":
    success, message = test_tigerbeetle_connection()
    if success:
        logger.info(f"TigerBeetle connection check PASSED: {message}")
    else:
        logger.error(f"TigerBeetle connection check FAILED: {message}")
