#!/usr/bin/env python3
import os
import sys
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, parent_dir)

import datetime
import security_i
import mysql.connector

import config_i
from database_i import get_connection

def get_iota_mnemonic(user_id: str, TESTING = False) -> str:
    """
    Returns the wallet path and password for the given user_id.

    :param user_id: The user ID (Atavism account ID)
    :return: (wallet_address, wallet_password)
    :raises: Runtime error if the user is not found
    """
    #sys.stdout = open(__file__ + '.log', 'a')
    #sys.stderr = sys.stdout
    #print(f"\n{datetime.datetime.now()}")

    if TESTING: print (f"get_iota_mnemonic.py: Getting mnemonic for user {user_id}...")
    conn = get_connection (config_i.config.db.tr1)
    cursor = conn.cursor()
    #cursor.execute("SELECT wallet_im FROM users WHERE user_id = %s", (user_id,))
    cursor.execute("SELECT wallet_m FROM users WHERE user_id = %s", (user_id,))
    result = cursor.fetchone()
    conn.close()

    #print (f"get_iota_mnemonic.py: Result: {result}")
    if not result:
        raise RuntimeError(f"No wallet found for user {user_id}")

    return security_i.decrypt(result[0])

# Optional CLI usage for debugging
if __name__ == "__main__":
    import sys
    if len(sys.argv) < 2:
        print("Usage: get_iota_mnemonic.py <user_id> [test]")
        #i = 43
        #print (i, " - ", get_iota_mnemonic(i), end="\n", file=sys.__stdout__)
        exit(1)        
    try:
        mnemonic = get_iota_mnemonic(sys.argv[1], False)
        print(mnemonic, end="", file=sys.__stdout__)
    except RuntimeError as e:
        print(e)
        exit(1)

#19 - iota testnet - want turkey panda dice wrist all disease promote alcohol acoustic animal phone mother tube panda million tomorrow renew tornado pet siege advice spoon example

