import logging, os

from os.path import exists

# Hint how to edit the settings and quit
def hint_quit():
	logging.info("")
	logging.info("    edit local_settings.py")
	logging.info("")
	quit()

# Copy or create settings file if missing
def missing_config():
	logging.basicConfig(level=logging.DEBUG)
	if not exists("local_settings.py"):
		logging.error("Settings file not found.")
		logging.info("Copying local_settings_example.py to local_settings.py")
		try:
			os.system("cp local_settings_example.py local_settings.py")
		except FileNotFoundError:
			logging.info("local_settings_example.py not found, creating local_settings.py")
			with open("local_settings.py", "w") as settings_file:
				settings_file.writelines(
					[
						"import logging",
						"LOG_LEVEL = logging.INFO	# Options: CRITICAL, ERROR, WARNING, INFO, and DEBUG",
						"",
						"DATABASE_NAME = \"\"",
						"DATABASE_USER = \"\"",
						"DATABASE_HOST = \"\"",
						"DATABASE_PASSWORD = \"\"",
						"",
						"WEB_HOST = \"\"",
						"WEB_SCHEME = \"\"",
						"",
						"DISCORD_TOKEN = \"\"",
						"COMMAND_PREFIX = \"\"",
					]
				)
	logging.error("Settings undefined.")
	logging.info("Configure the settings:")
	hint_quit()

# Hint to correct specific setting and quit
def correct_setting(setting):
	logging.info("Correct the %s in local_settings.py", setting)
	hint_quit()

# Import settings
try:
	import local_settings as settings   # Environment dependant settings stored in local_settings.py, untracked by .gitinore
except ModuleNotFoundError:
	missing_config()

# Check additional settings
if not settings.WEB_HOST:
	logging.error("Web host undefinded.")
	correct_setting("WEB_HOST")
	
if not settings.WEB_SCHEME:
	logging.error("Web scheme undefinded.")
	correct_setting("WEB_SCHEME")

# Set loglevel
try:
	logging.basicConfig(level=settings.LOG_LEVEL)
except AttributeError:
	missing_config()

# Define database pool
import asyncpg
async def create_db_pool():
	try:
		bot.pg = await asyncpg.create_pool(
			database=settings.DATABASE_NAME,
			user=settings.DATABASE_USER,
			host=settings.DATABASE_HOST,
			password=settings.DATABASE_PASSWORD,
		)
	except AttributeError:
		missing_config()

# Create robot
import discord
from discord.ext import commands
try:
	bot = commands.Bot(
		command_prefix = settings.COMMAND_PREFIX,
		description = "Charlie's Angels bot",
		intents = discord.Intents.default(),    # Required: Guilds
		case_insensitive = True,
	)
except AttributeError:
	print("Attribute error on create.")
	missing_config()

# Create database pool
bot.loop.run_until_complete(create_db_pool())

# Create database tables if they do not exist
from query.initialise_database import init_db
bot.loop.run_until_complete(init_db(bot.pg))

# Load extensions
default_extensions = [
	"commands.admin",
	"commands.games",
	"commands.general",
	"events.general",
]
for ext in default_extensions:
  bot.load_extension(ext)

# Run robot
try:
	bot.run(settings.DISCORD_TOKEN)
except AttributeError:
	print("Attribute error on run.")
	missing_config()
except discord.errors.LoginFailure:
	logging.error("Invalid discord token.")
	correct_setting("DISCORD_TOKEN")