#!/usr/bin/env python3

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

import mysql.connector
from config_i import config
from database_i import get_connection
import create_iota_user
import os
import sys

def get_iota_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_i FROM users WHERE user_id = %s", (user_id,))
    result = cursor.fetchone()
    conn.close()

    #if TESTING: print (f"get_smr_address.py: Result: {result}")
    if result is None or result[0] is None or result[0] == "":
        #print (f"{datetime.datetime.now()}: get_iota_address.py | User {user_id} not found; creating new user and wallet.", file=sys.stderr)
        create_iota_user.main(user_id)
    return result[0]

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