# This script initializes TeLLMgramBot with useful functions
import os
import sys

# Handle relative modules if running this script vs. elsewhere
try:
    from .utils import read_text, generate_file_path
except ImportError:
    from utils import read_text, generate_file_path

INIT_BOT_CONFIG = {
    'bot_username': 'test_bot',
    'bot_owner': '<YOUR USERNAME>',
    'bot_name': 'Test Bot',
    'bot_nickname': 'Testy',
    'bot_initials': 'TB',
    'chat_model': 'gpt-5-mini',
    'url_model': 'gpt-5',
    'token_limit': None,
    'persona_temp': None,
    'persona_prompt': 'You are a test harness bot.'
}

def execution_dir() -> str:
    """
    Initializes the top-level execution's path directory
    """
    execution = os.path.abspath(sys.argv[0])
    if os.path.basename(execution) == 'initialize.py':
        execution = os.path.dirname(execution)
    return os.path.dirname(execution)

# Checks for important directories to configure for TeLLMgramBot
# If each environment variable is not defined, set directory with base execution path:
# - TELLMGRAMBOT_CONFIGS_PATH
# - TELLMGRAMBOT_PROMPTS_PATH
# - TELLMGRAMBOT_ERRORLOGS_PATH
# - TELLMGRAMBOT_SESSIONLOGS_PATH
def init_directories():
    for directory in ['configs', 'prompts', 'errorlogs', 'sessionlogs']:
        env_var = f"TELLMGRAMBOT_{directory.upper()}_PATH"
        if not os.environ.get(env_var):
            os.environ[env_var] = os.path.join(execution_dir(), directory)
            try:
                if not os.path.exists(os.environ[env_var]):
                    os.makedirs(os.environ[env_var])
                    print(f"Created {env_var} directory: {os.environ[env_var]}")
            except Exception as e:
                sys.exit(f"{type(e).__name__} on {env_var} directory '{os.environ[env_var]}': {e}\nExiting...")

# TeLLMgramBot utilizes three API keys by environment variable first then .key file:
# - TELLMGRAMBOT_OPENAI_API_KEY
# - TELLMGRAMBOT_TELEGRAM_API_KEY
# - TELLMGRAMBOT_VIRUSTOTAL_API_KEY
# - TELLMGRAMBOT_KEYS_PATH (otherwise base application path) for key files:
#   + openai.key
#   + telegram.key
#   + virustotal.key 
def init_keys():
    # List each key and URL if it does not exist for more information
    keys = {
        'openai': 'https://platform.openai.com/api-keys',
        'telegram': 'https://core.telegram.org/api',
        'virustotal': 'https://developers.virustotal.com/reference/overview'
    }
    # Ensure appropriate keys can be populated from environment variables or files
    keys_need = 0
    for key, url in keys.items():
        env_var = f"TELLMGRAMBOT_{key.upper()}_API_KEY"
        # If the environment variable is undefined, set by API key file
        if not os.environ.get(env_var):
            path = os.path.join(os.environ.get('TELLMGRAMBOT_KEYS_PATH', execution_dir()), f"{key}.key")
            if not os.path.exists(path):
                # Create a basic *.key file for user to input next run
                generate_file_path(os.path.dirname(path), os.path.basename(path), (
                    f"YOUR {key.upper()} API KEY HERE - {url}\n"
                ), "API key")
                keys_need = 1
                continue
            else:
                # Load each API key by file into its environment variable
                os.environ[env_var] = read_text(path)
                print(f"Loaded {env_var} secret from: {path}")

        # API keys must be defined and not have any spaces
        if not os.environ.get(env_var) or any(c.isspace() for c in os.environ.get(env_var)):
            print(f"{env_var} secret cannot be blank or have any whitelines")
            keys_need = 1

    # Stop program if one of the API keys is needed or has an error
    if keys_need:
        sys.exit("Need appropriate API keys to run TeLLMgramBot! Exiting...")

# Ensure the list of TeLLMgramBot commands is provided for user by a text file
def init_bot_commands(file='commands.txt') -> str:
    env_var = "TELLMGRAMBOT_CONFIGS_PATH"
    try:
        return generate_file_path(os.environ[env_var], file, (
            "TeLLMgramBot commands:\n"
            "/start - Go online (Admin only)\n"
            "/stop - Go offline (Admin only)\n"
            "/nick - Add your nickname to set\n"
            "/forget - Clear your conversations\n"
            "/help - Show this information\n\n"
            "NOTE: Chat history will still show in your Telegram client. You must have a username, which is your "
            "default nickname unless specified like \"/nick B0b #2\".\n"
        ), 'Telegram commands')
    except KeyError:
        sys.exit(f"{env_var} must be defined to create file '{file}'! Exiting...")
    except Exception:
        sys.exit(f"Error while generating {env_var} file '{file}'! Exiting...")

# Ensure bot configuration file is created
def init_bot_config(file='config.yaml') -> str:
    env_var = "TELLMGRAMBOT_CONFIGS_PATH"
    try:
        path = os.path.join(os.environ[env_var], file)
        if not os.path.exists(path):
            # Create a basic TeLLMgramBot configuration by filename
            generate_file_path(os.path.dirname(path), file, "", "bot configuration")
            with open(path, 'w') as f:
                # Add configuration with default values except prompt:
                for parameter, value in INIT_BOT_CONFIG.items():
                    if parameter == 'persona_prompt':
                        next
                    else:  # Write parameter, with optional comment if no value
                        f.write('%s : %s\n' % (
                            parameter.ljust(12),
                            value if value else '# Optional, see README'
                        ))
        return path
    except KeyError:
        sys.exit(f"{env_var} must be defined to create file '{file}'! Exiting...")
    except Exception:
        sys.exit(f"{type(e).__name__} on {env_var} file '{file}': {e}\nExiting...")

# Ensures TokenGPT configuration file is created
def init_tokenGPT_config(file='tokenGPT.yaml') -> str:
    env_var = "TELLMGRAMBOT_CONFIGS_PATH"
    try:
        # Create a basic GPT configuration of token parameters by filename
        return generate_file_path(os.environ[env_var], file, (
            "# Available parameters per base OpenAI model with default values:\n"
            "#   max_tokens: 4097\n"
            "#   tokens_per_message: 3\n"
            "#   tokens_per_name: 1\n"
            "# For OpenAI's updated list of models, please see:\n"
            "#   https://platform.openai.com/docs/models\n"
            "'gpt-4o':\n"
            "  max_tokens: 128000\n"
            "'gpt-4o-mini':\n"
            "  max_tokens: 128000\n"
            "'gpt-5':\n"
            "  max_tokens: 400000\n"
            "'gpt-5-mini':\n" 
            "  max_tokens: 400000\n"
            "'gpt-5-nano':\n"
            "  max_tokens: 400000\n"
        ), "TokenGPT configuration")
    except KeyError:
        sys.exit(f"{env_var} must be defined to create file '{file}'! Exiting...")
    except Exception:
        sys.exit(f"Error while generating {env_var} file '{file}'! Exiting...")

# Ensure prompt file is created that defines bot personality
def init_bot_prompt(file='test_personality.prmpt') -> str:
    env_var = "TELLMGRAMBOT_PROMPTS_PATH"
    try:
        return generate_file_path(os.environ[env_var], file, (
            "You are a test harness bot based on a GPT-5 mini model that can:\n"
            "1. Fetch URLs, provided the user supply a URL in [square brackets].\n"
            "2. Scrub URLs to ensure they are safe for work via the VirusTotal API.\n"
        ), "bot personality prompt")
    except KeyError:
        sys.exit(f"{env_var} must be defined to create file '{file}'! Exiting...")
    except Exception:
        sys.exit(f"Error while generating {env_var} file '{file}'! Exiting...")

# Ensure prompt file is created that defines how the bot will analyze URLS via square brackets []
def init_url_prompt(file='url_analysis.prmpt') -> str:
    env_var = "TELLMGRAMBOT_PROMPTS_PATH"
    try:
        return generate_file_path(os.environ[env_var], file, (
            "The user has provided a URL to perform some level of analysis. You will infer the nature of the "
            "analysis from the user's query.\n\n"
            "The contents of the URL mentioned have already been harvested and cleansed. Note the URL contents "
            "will likely have sections of text that are less relevant to the user's question (headers, footers, "
            "menus, ads, etc.). You will need to ignore those sections of text and focus on the main content of "
            "the page.\n\n"
            "The contents of the URL are shown below:\n"
            "BEGIN URL CONTENTS\n"
            "{url_content}\n"
            "END URL CONTENTS\n"
        ), "URL analysis prompt")
    except KeyError:
        sys.exit(f"{env_var} must be defined to create file '{file}'! Exiting...")
    except Exception:
        sys.exit(f"Error while generating {env_var} file '{file}'! Exiting...")
    return path

# Performs main setup, especially with necessary files
def init_structure():
    init_directories()
    init_keys()
    init_url_prompt()
    init_tokenGPT_config()
    init_bot_commands()

# Run this script if the first time setting up TeLLMgramBot
if __name__ == '__main__':
    init_structure()
    init_bot_config()
    init_bot_prompt()
    print("TeLLMgramBot setup complete!")
