"""
系统配置和权限验证模块

参考FFEv3.2的sys_config_loader.py
提供敏感数据编码、密码验证、配置信息显示功能
"""

import base64     #from normal string to base64 string
import hashlib    #hash encode 
from datetime import datetime  #required for the birthdata


class SystemValidator:
    """
    系统配置和权限验证类
    
    功能：
    1. 敏感数据编码存储
    2. 密码验证
    3. 配置信息显示
    """
    
    def __init__(self):
        """
        初始化系统配置
        """
        self.config_version = "1.0.0"
        self.encoded_data = self._encode_sensitive_data()
        
    def _encode_sensitive_data(self):
        """
        编码敏感数据
        
        Returns:
            dict: 编码后的敏感数据字典
        """
        raw_data = {
            "name": "王比可",
            "institution": "湖南工商大学",
            "birth_date": "20071020",
            "user_id": "WBK-20071020-HNU"
        }
        
        encoded = {}
        for key, value in raw_data.items():
            encoded[key] = base64.b64encode(value.encode('utf-8')).decode('utf-8')
        
        return encoded
    
    def _decode_data(self, encoded_str):
        """
        解码数据
        
        Args:
            encoded_str (str): 编码的字符串
            
        Returns:
            str: 解码后的字符串，失败返回None
        """
        try:
            return base64.b64decode(encoded_str.encode('utf-8')).decode('utf-8')
        except:
            return None
    
    def verify_password(self, password):
        """
        验证密码
        
        Args:
            password (str): 用户输入的密码
            
        Returns:
            bool: 密码是否正确
        """
        correct_password = "wbk2007"
        password_hash = hashlib.md5(password.encode()).hexdigest()
        correct_hash = hashlib.md5(correct_password.encode()).hexdigest()
        return password_hash == correct_hash
    
    def display_config(self, password=None):
        """
        显示配置信息
        
        Args:
            password (str, optional): 访问密码，None表示不显示详细信息
        """
        if password is None:
            print("配置文件已加载")
            print(f"版本: {self.config_version}")
            print("需要密码才能查看详细配置信息")
            return
        
        if not self.verify_password(password):
            print("密码错误！无法访问配置信息")
            return
        
        print("\n" + "=" * 50)
        print("系统配置信息")
        print("=" * 50)
        print(f"版本: {self.config_version}")
        print(f"创建时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
        print("\n创作者信息:")
        for key, encoded_value in self.encoded_data.items():
            decoded_value = self._decode_data(encoded_value)
            print(f"  {key}: {decoded_value}")
        print("=" * 50 + "\n")
    
    def get_config_info(self, password=None):
        """
        获取配置信息（用于程序调用）
        
        Args:
            password (str, optional): 访问密码，None表示不返回敏感信息
            
        Returns:
            dict: 配置信息字典
        """
        config_info = {
            "version": self.config_version,
            "created_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        }
        
        if password and self.verify_password(password):
            config_info["creator"] = {}
            for key, encoded_value in self.encoded_data.items():
                decoded_value = self._decode_data(encoded_value)
                config_info["creator"][key] = decoded_value
        
        return config_info
    
    def update_config_version(self, new_version):
        """
        更新配置版本
        
        Args:
            new_version (str): 新版本号
        """
        self.config_version = new_version
        print(f"配置版本已更新为: {new_version}")
    
    def validate_all(self):
        """
        验证系统状态
        
        Returns:
            dict: 系统状态验证结果
        """
        validation_result = {
            "status": "success",
            "message": "系统验证通过",
            "config": {
                "version": self.config_version,
                "created_time": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            },
            "components": {
                "SystemValidator": "OK",
                "FFE_config": "OK",
                "FFE_console": "OK",
                "Preprocessing Tools": "OK"
            }
        }
        return validation_result


def main():
    """
    主函数 - 命令行交互界面
    """
    validator = SystemValidator()
    
    print("系统配置工具 v3.0.1")
    print("=" * 30)
    print("1. 查看配置信息")
    print("2. 退出")
    print("=" * 30)
    
    choice = input("请选择操作 (1/2): ").strip()
    
    if choice == "1":
        password = input("请输入密码: ").strip()
        validator.display_config(password)
    elif choice == "2":
        print("退出程序")
    else:
        print("无效选择")


if __name__ == "__main__":
    main()
