import atexit
import os
import pkgutil
import shutil
import sqlite3
import sys
from typing import Optional

from common.log import logger

connection: Optional[sqlite3.Connection] = None


def init_global_db_connection(db_path='./local.db'):
    global connection
    output_directory = os.path.dirname(sys.executable)
    db_file = os.path.join(output_directory, 'sqlite.db')
    if not os.path.exists(db_file):
        template_file = resource_path('template.db')
        destination_file = os.path.join(output_directory, 'sqlite.db')

        if template_file:
            shutil.copyfile(template_file, destination_file)
        else:
            print(f"模板文件 template.db 不存在")
    else:
        print(f"{db_file} 已存在")
    connection = sqlite3.connect('./sqlite.db')
    print("SQLite connection is established.")


def get_global_db_connection():
    return connection


def close_global_db_connection():
    global connection
    if connection is not None:
        connection.close()
        connection = None
        print("SQLite connection is closed.")


def init_new_db_connection(db_path='./sqlite.db'):
    return sqlite3.connect(db_path)


def resource_path(relative_path):
    # Function to get the absolute path to resources
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

