# -*- coding: utf-8 -*-
from pydantic import BaseSettings, Field
from functools import lru_cache
from typing import Optional
from dotenv.main import DotEnv
from extensions import logger
from contextlib import contextmanager
import os
import io
from io import StringIO

def my_get_stream(self):
    if isinstance(self.dotenv_path, StringIO):
        yield self.dotenv_path
    elif os.path.isfile(self.dotenv_path):
        with io.open(self.dotenv_path, encoding='utf-8') as stream:
            yield stream
    else:
        if self.verbose:
            logger.warning("File doesn't exist %s", self.dotenv_path)
        yield StringIO('')


DotEnv._get_stream = contextmanager(my_get_stream)

class Settings(BaseSettings):

    # 系统环境
    ENVIRONMENT: Optional[str] = Field(None, env="ENVIRONMENT")

    SECRET_KEY = "09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7"
    ALGORITHM = "HS256"

    REDIS_DB_URL = {}
    mysql_dwd_config = {}

    class Config:
        env_file = ".env"


class DevConfig(Settings):

    REDIS_DB_URL = {
        'host': '127.0.0.1',
        'port': 6379,
        'password': 'c0b0Info@)!%',
        'db': 0
    }

    mysql_dwd_config = {
        'drivername': 'mysql+pymysql',
        'username': 'root',
        'password': 'c0b0Info@)!%',
        'host': '127.0.0.1',
        'port':3306 ,
        'database': 'ry-vue'
    }

class ProdConfig(Settings):

    REDIS_DB_URL = {
        'host': '127.0.0.1',
        'port': 6379,
        'password': 'c0b0Info@)!%',
        'db': 0
    }

    mysql_dwd_config = {
        'drivername': 'mysql+pymysql',
        'username': 'dba',
        'password': 'ClwXOB~A8f*Q3ijx',
        'host': '10.181.7.237',
        'port':3306 ,
        'database': 'mmyjhd'
    }

class FactoryConfig:
    """Returns a config instance dependending on the ENV_STATE variable."""

    def __init__(self, env_state: Optional[str]):
        self.env_state = env_state

    def __call__(self):

        if self.env_state == "development":
            return DevConfig()

        elif self.env_state == "production":
            return ProdConfig()
        
        else:
            return DevConfig()


@lru_cache()
def get_configs():
    from dotenv import load_dotenv
    load_dotenv(encoding='utf-8')
    return FactoryConfig(Settings().ENVIRONMENT)()

settings = get_configs()
