import importlib.resources as pkg_resources
import os
from pathlib import Path
from uuid import uuid4


class ConfigGen:
    def __init__(self):
        self.__db_connection_string: str = 'sqlite'
        self.__db_name: str = None
        self.__db_user: str = None
        self.__db_password: str = None
        self.__db_host: str = None
        self.__db_port: str = None
        self.__secret_key: str = None
        self.__allowed_hosts: list = None
        self.__debug: bool = True
        self.__root_dir: Path = self.__set_root_path()
        self.__envs_dir: Path = self.__set_envs_path()

    @staticmethod
    def __set_root_path():
        root_package_name = __name__.split('.')[0]

        if root_package_name == '__main__':
            return Path(__file__).resolve().parent.parent
        else:
            return pkg_resources.files(root_package_name)

    def __set_envs_path(self):
        envs_path = self.__root_dir / 'envs'
        os.makedirs(envs_path, exist_ok=True)
        return envs_path

    def create_envfile_default(self):
        """Creates a default .env file in the root directory."""
        self.__db_name = uuid4()

        with open(self.__root_dir / '.env', 'w', encoding='utf-8') as env_file:
            env_file.write(
                f"""# .env file generated by ConfigGen
DB_CONNECTION_STRING='{self.__db_connection_string}'
DB_NAME='{self.__db_name}'
"""
            )

    def create_settings_default(self):
        """Creates a default settings.py file in the root directory."""
        with open(self.__root_dir / 'settings.py', 'w', encoding='utf-8') as pyfile:
            pyfile.write(
                """import os
from dotenv import load_dotenv


class Settings:
    load_dotenv(".env")
    DB_CONNECTION_STRING: str = os.getenv("DB_CONNECTION_STRING")
    DB_NAME: str = os.getenv("DB_NAME")
    DB_URL: str = f"{DB_CONNECTION_STRING}:///{DB_NAME}"
settings: Settings = Settings()
"""
            )
