'''Essentials for the bot to function'''
import configparser
import os
import sys
import argparse

def get_config_file_path():
    """Get config file path from command line arguments or default"""
    parser = argparse.ArgumentParser(add_help=False)  # Don't interfere with other argument parsing
    parser.add_argument('--config', default='config.ini', help='Path to config file (default: config.ini)')
    
    # Parse only known args to avoid conflicts with other argument parsing
    args, _ = parser.parse_known_args()
    return args.config

def load_config():
    """Load and validate config file with proper error handling"""
    config_file = get_config_file_path()
    config = configparser.ConfigParser()
    
    # Check if config file exists
    if not os.path.exists(config_file):
        print(f"Error: {config_file} not found!")
        if config_file == 'config.ini':
            print("Please copy example_config.ini to config.ini and configure it.")
        print(f"Or use --config /path/to/your/config.ini to specify a different location.")
        sys.exit(1)
    
    try:
        config.read(config_file)
    except configparser.Error as e:
        print(f"Error reading {config_file}: {e}")
        sys.exit(1)
    
    # Check if [application] section exists
    if 'application' not in config:
        print(f"Error: [application] section missing in {config_file}")
        sys.exit(1)
    
    # Validate required fields
    required_fields = ['BotUser', 'ApiKey', 'InstanceUrl', 'InstanceType', 'DatabaseLocation']
    missing_fields = []
    
    for field in required_fields:
        if field not in config['application'] or not config['application'][field].strip():
            missing_fields.append(field)
    
    if missing_fields:
        print(f"Error: Required fields missing in {config_file}: {', '.join(missing_fields)}")
        sys.exit(1)
    
    # Validate InstanceType
    instance_type = config['application']['InstanceType'].lower()
    if instance_type not in ('misskey', 'pleroma'):
        print("Error: InstanceType must be either 'misskey' or 'pleroma'")
        sys.exit(1)
    
    return config

# Load and validate configuration
config = load_config()

# Username for the bot
USER = config['application']['BotUser']

# API key for the bot
KEY = config['application']['ApiKey']

# Bot's instance URL
INSTANCE = config['application']['InstanceUrl']

# SQLite Database location
DB_PATH = config['application']['DatabaseLocation']

# Instance type
INSTANCE_TYPE = config['application']['InstanceType'].lower()

# Web server port
WEB_PORT = config['application'].getint('WebPort', 5000)

# Trusted instances
trusted_instances_str = config['application'].get('TrustedInstances', '')
TRUSTED_INSTANCES = [instance.strip() for instance in trusted_instances_str.split(',') if instance.strip()]

# Extra stuff for control of the bot

# TODO: move this to db
# Fedi handles in the traditional 'user@domain.tld' style, allows these users
# to use extra admin exclusive commands with the bot'''
ADMINS = config['application'].get('DefaultAdmins', '[]')