#!/usr/bin/env python3
import logging
logging.basicConfig(level=logging.DEBUG)

import database

def get_account_id_from_character_id(character_id: str, TESTING = False) -> str:
    """
    Returns the account ID for the given character ID.

    :param character_id: The character ID
    :return: (account_id)
    :raises: Runtime error if the character is not found
    """
    #if TESTING: print (f"atavism.py: Getting account ID for character {character_id}...")
    conn = database.get_connection (database.config.db.atavism.master)
    cursor = conn.cursor()
    cursor.execute("SELECT account_id FROM account_character WHERE character_id = %s", (character_id,))
    result = cursor.fetchone()
    conn.close()

    #if TESTING: print (f"atavism.py: Result: {result}")
    if not result:
      raise RuntimeError(f"No account found for character {character_id}")

    #logging.debug(f"get_account_id_from_character_id ||{result[0]}||")
    return result[0]


# Optional CLI usage for debugging
if __name__ == "__main__":
    import sys
    if len(sys.argv) < 2:
        logging.debug("Usage: get_account_id_from_character_id.py <character_id> [test]")
        logging.debug(f"get_account_id_from_character_id | TEST ||{get_account_id_from_character_id(62463)}||")
        exit(1)
    try:
        address = get_account_id_from_character_id(sys.argv[1], True)
        print(address, end="")
    except RuntimeError as e:
        logging.debug(e)
        exit(1)