#!/usr/bin/env python3

import logging
import datetime
logging.basicConfig(level=logging.DEBUG)

import mysql.connector
from config import config
from database import get_connection
import create_smr_user
import os
import sys

def get_smr_address(user_id: str, TESTING = False) -> str:
    """
    Returns the address of the Shimmer wallet for the given user_id.

    :param user_id: The user ID (Atavism account ID)
    :return: (wallet_address)
    :raises: Runtime error if the user is not found
    """
    #if TESTING: print (f"get_smr_address.py: Getting Shimmer wallet address for user {user_id}...")
    conn = get_connection (config.db.tr1)
    cursor = conn.cursor()
    cursor.execute("SELECT wallet_a FROM users WHERE user_id = %s", (user_id,))
    result = cursor.fetchone()
    conn.close()

    #if TESTING: print (f"get_smr_address.py: Result: {result}")
    if not result:
        print (f"{datetime.datetime.now()}: get_smr_address.py | User {user_id} not found; creating new user and wallet.", file=sys.stderr)
        create_smr_user.main(user_id)
        #return "Continuing in get_smr_address."
            #return get_smr_address(user_id, TESTING)
        #else:
        #    return "No wallet, and wallet-creation failed."

    #logging.debug(f"get_smr_address.py | Address: {result[0]}||")
    return result[0]

# Optional CLI usage for debugging
if __name__ == "__main__":
    import sys
    if len(sys.argv) < 2:
        logging.debug("get_smr_address.py | Usage: get_wallet_credentials.py <user_id> [test]")
        logging.debug (f"get_smr_address.py | TEST ||{get_smr_address(21)}||")
        print(f"we're back in main, now.", flush=True)
        exit(0)
    try:
        address = get_smr_address(sys.argv[1], True)
        print (address, end="")
        logging.debug(f"get_smr_address.py | Address: {address}||")
        exit(0)
    except RuntimeError as e:
        logging.debug(e)
        exit(1)
