import uvicorn
import logging
from injector import Injector
from src.configuration import singleton

# TODO: 當 skip_ssl 功能加入主分支後移除複制的代嗎，改為使用pip安裝依賴。
from src.loki_logger_handler.loki_logger_handler import LokiLoggerHandler

import yaml

@singleton
class Main():

    def init_log_handlers(self):
        with open(".env.yaml", "r") as file:
            config = yaml.safe_load(file)
            try:
                log_handler_confg = config["log"]["handlers"]
                log_handlers = [logging.StreamHandler()]
                for handler_config in log_handler_confg:
                    if handler_config["type"] == "loki":
                        log_handlers.append(LokiLoggerHandler(
                        url=handler_config["url"],
                        additional_headers={"X-Odin-Auth": handler_config["x-odin-auth"]},
                        labels=handler_config["labels"],
                        label_keys={},
                        timeout=10,
                        enable_structured_loki_metadata=True,
                        loki_metadata={"service": "user-service", "version": "1.0.0"},
                        insecure_ssl_verify=False
                    ))
                logging.basicConfig(level=logging.DEBUG, handlers=log_handlers)
                logging.info("logging init finish")
            except KeyError:
                return
                
    def __init__(self) -> None:
        self.init_log_handlers()
            
    def run(self):
        logger = logging.getLogger(__name__)
        logger.info("jarvis-models start", extra={"version": "0.0.1"})
        uvicorn.run("server:app", host="0.0.0.0", port=8000, log_level="info",reload = True)

if __name__ == "__main__":
    injector = Injector()
    main = injector.get(Main)
    main.run()