#!/usr/bin/env python3
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}")

  return result[0]


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