import os, sys, json
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, parent_dir)

# Reuse your existing helpers
from get_account_id_from_character_id_i import get_account_id_from_character_id
from get_wallet_credentials_i import get_wallet_credentials

# TODO: implement this to write to your DB (address + optional mnemonic)
def upsert_iota_wallet_in_db(user_id: int, address: str, mnemonic: str | None) -> None:
    # Example only — replace with your real DB call
    # db.execute("UPDATE users SET iota_address=%s, iota_mnemonic=%s WHERE id=%s",
    #            (address, mnemonic, user_id))
    pass

def main(character_id: str) -> str:
    user_id = get_account_id_from_character_id(character_id)

    # Keep your current flow: this should create/ensure and return the address.
    # If your get_wallet_credentials() can surface a mnemonic on creation, return it here;
    # otherwise 'mnemonic' will be None and only the address is stored.
    creds = get_wallet_credentials(user_id, TESTING=True)
    if isinstance(creds, (list, tuple)):
        address = creds[0]
        mnemonic = creds[1] if len(creds) > 1 and creds[1] else None
    else:
        address, mnemonic = str(creds), None

    upsert_iota_wallet_in_db(user_id, address, mnemonic)
    print(address, end="")  # plain text body for Unity/PHP
    return address

if __name__ == "__main__":
    char_id = sys.argv[1] if len(sys.argv) > 1 else ""
    if not char_id:
        print("Missing characterId", file=sys.stderr); sys.exit(1)
    main(char_id)
