import os
import pathlib

from service.config._settings import ProjectSettings

__all__ = ["ROOT_DIR", "TORTOISE_ORM", "settings", "LOGGING"]
ROOT_DIR = pathlib.Path(__file__).parent.parent.parent
settings = ProjectSettings()
os.environ.update({"APP_NAME": settings.project_name})

TORTOISE_ORM = {
    "connections": {"default": settings.database_url},
    "apps": {
        "service": {
            "models": ["service.database.models", "aerich.models"],
            "default_connection": "default",
        },
    },
    "use_tz": True,
}

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "filters": {},
    "root": {"level": settings.log_level},
    "formatters": {
        "structured": {
            "()": "setech.logging.LogJSONFormatter",
        },
        "simple": {
            "format": "[%(asctime)s] %(levelname)-4s: %(message)s",
            "datefmt": "%F %T",
        },
        "precise": {
            "format": "[%(asctime)s][%(levelname)-4s][%(filename)s:%(funcName)s:%(lineno)s: %(message)s",
            "datefmt": "%F %T %z",
        },
    },
    "handlers": {
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "simple",
        },
        "console_json": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "structured",
        },
        "console_precise": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "precise",
        },
        "query_file": {
            "level": "INFO",
            "class": "logging.FileHandler",
            "filename": "logs/query.log",
            "formatter": "structured",
        },
    },
    "loggers": {
        "tasks": {
            "level": "INFO",
            "handlers": ["console"],
            "propagate": False,
        },
        "service": {
            "level": "INFO",
            "handlers": ["console"],
            "propagate": False,
        },
        "api": {
            "level": "INFO",
            "handlers": ["console_json"],
            "propagate": False,
        },
        "crud.journal": {
            "level": "DEBUG",
            "handlers": ["console_json"],
            "propagate": False,
        },
        "tortoise.db_client": {
            "level": "DEBUG",
            "handlers": ["console_precise", "query_file"],
            "propagate": False,
        },
    },
}
