import os
from pathlib import Path
import yaml


class Settings:
    secret_key: str = ''
    sgb_base_url: str = ''
    sgb_websocket_url: str = ''
    fwr_base_url: str = ''
    database_url: str = ''
    sgb_db_url: str = ''
    fwr_db_url: str = ''
    fetch_sgb_agent: str = ''
    fetch_fwr_agent: str = ''
    PUBLIC_KEY: str
    PRIVATE_KEY: str
    PASSWORD_KEY: str
    basic_base_url: str = ''
    basic_paper_url: str = ''
    dify_base_url: str = ''
    dify_api_token: str = ''
    dify_workflow_clean: str = ''
    dify_workflow_report: str = ''
    postgresql_database_url: str = ''
    dify_database_url: str = ''
    def __init__(self, **kwargs):
        # 替换配置中的IP地址
        # host_ip = os.getenv('HOST_IP', '127.0.0.1')
        # kwargs['sgb_base_url'] = kwargs.get('sgb_base_url', '').replace('127.0.0.1', host_ip)
        # kwargs['sgb_websocket_url'] = kwargs.get('sgb_websocket_url', '').replace('127.0.0.1', host_ip)
        # kwargs['fwr_base_url'] = kwargs.get('fwr_base_url', '').replace('127.0.0.1', host_ip)
        # kwargs['sgb_db_url'] = kwargs.get('sgb_db_url', '').replace('127.0.0.1', host_ip)
        # kwargs['fwr_db_url'] = kwargs.get('fwr_db_url', '').replace('127.0.0.1', host_ip)
        # kwargs['dify_base_url'] = kwargs.get('dify_base_url', '').replace('127.0.0.1', host_ip)
        # kwargs['basic_base_url'] = kwargs.get('basic_base_url', '').replace('127.0.0.1', host_ip)
        # kwargs['dify_database_url'] = kwargs.get('dify_database_url', '').replace('127.0.0.1', host_ip)
        # Check if all required fields are provided and set them
        for field in self.__annotations__.keys():
            if field not in kwargs:
                raise ValueError(f"Missing setting: {field}")
            setattr(self, field, kwargs[field])

    def to_dict(self):
        """Return the settings as a dictionary."""
        return {k: getattr(self, k) for k in self.__annotations__.keys()}

    def __repr__(self):
        """Return a string representation of the settings."""
        return f"Settings({self.to_dict()})"


def load_yaml(file_path: Path) -> dict:
    with file_path.open('r', encoding="utf-8") as fr:
        try:
            data = yaml.safe_load(fr)
            return data
        except yaml.YAMLError as e:
            print(f"Error loading YAML file {file_path}: {e}")
            return {}


# Use pathlib to handle file paths
# config_yaml_path = os.path.join(os.path.join(Path(__file__).parent, "env_conf"), "config.yaml")
config_yaml_path = Path(__file__).parent.joinpath("env_conf") / 'config.yaml'
print(config_yaml_path)
settings_data = load_yaml(config_yaml_path)

# Initialize settings object
settings = Settings(**settings_data)

# Print the loaded settings
print(f"Loaded settings: {settings}")
