import os
import configparser
import json
import xml.etree.ElementTree as ET
import yaml
from abc import ABC, abstractmethod

class ConfigEngine(ABC):
    @abstractmethod
    def load(self, file_path):
        pass

    @abstractmethod
    def save(self, data, file_path):
        pass

# INI 引擎
class INIEngine(ConfigEngine):
    def load(self, file_path):
        config = configparser.ConfigParser()
        config.read(file_path)
        return {section: dict(config[section].items()) for section in config.sections()}

    def save(self, data, file_path):
        config = configparser.ConfigParser()
        for section, values in data.items():
            config.add_section(section)
            for key, value in values.items():
                config.set(section, key, str(value))
        with open(file_path, 'w') as configfile:
            config.write(configfile)

# JSON 引擎
class JSONEngine(ConfigEngine):
    def load(self, file_path):
        with open(file_path, 'r') as file:
            return json.load(file)

    def save(self, data, file_path):
        with open(file_path, 'w') as file:
            json.dump(data, file, indent=2)

# YAML 引擎
class YAMLEngine(ConfigEngine):
    def load(self, file_path):
        with open(file_path, 'r') as file:
            return yaml.safe_load(file)

    def save(self, data, file_path):
        with open(file_path, 'w') as file:
            yaml.dump(data, file, default_flow_style=False)

# XML 引擎
class XMLEngine(ConfigEngine):
    def load(self, file_path):
        tree = ET.parse(file_path)
        root = tree.getroot()
        return self._parse_xml(root)

    def _parse_xml(self, element):
        result = {}
        for child in element:
            if len(child) > 0:
                result[child.tag] = self._parse_xml(child)
            else:
                result[child.tag] = child.text
        return result

    def save(self, data, file_path):
        root = ET.Element("Configuration")
        self._build_xml(root, data)
        tree = ET.ElementTree(root)
        tree.write(file_path, encoding='utf-8', xml_declaration=True)

    def _build_xml(self, parent_element, data):
        for key, value in data.items():
            if isinstance(value, dict):
                child = ET.SubElement(parent_element, key)
                self._build_xml(child, value)
            else:
                child = ET.SubElement(parent_element, key)
                child.text = str(value)

# C/CC 引擎
class CEngine(ConfigEngine):
    def load(self, file_path):
        with open(file_path, 'r') as file:
            return file.read()

    def save(self, data, file_path):
        with open(file_path, 'w') as file:
            file.write(data)

# Java 引擎
class JavaEngine(ConfigEngine):
    def load(self, file_path):
        with open(file_path, 'r') as file:
            return file.read()

    def save(self, data, file_path):
        with open(file_path, 'w') as file:
            file.write(data)

# 总引擎管理器
class ConfigManager:
    def __init__(self):
        self.engines = {
            'ini': INIEngine(),
            'json': JSONEngine(),
            'yaml': YAMLEngine(),
            'xml': XMLEngine(),
            'c': CEngine(),
            'cc': CEngine(),
            'java': JavaEngine()
        }

    def load_config(self, file_path):
        file_extension = file_path.split('.')[-1]
        engine = self.engines.get(file_extension)
        if not engine:
            raise ValueError(f"不支持的文件格式: {file_extension}")
        return engine.load(file_path)

    def save_config(self, data, file_path):
        file_extension = file_path.split('.')[-1]
        engine = self.engines.get(file_extension)
        if not engine:
            raise ValueError(f"不支持的文件格式: {file_extension}")
        engine.save(data, file_path)

    def load_all_configs(self, directory):
        all_configs = {}
        for root, _, files in os.walk(directory):
            for file in files:
                file_path = os.path.join(root, file)
                try:
                    config_data = self.load_config(file_path)
                    all_configs[file_path] = config_data
                except ValueError as e:
                    print(e)
                except Exception as e:
                    print(f"无法加载文件 {file_path}: {e}")
        return all_configs

if __name__ == "__main__":
    import sys

    if len(sys.argv) < 2:
        print("用法: python config_manager.py {load|save|load-all} <文件路径或目录> [<目标文件路径>]")
        sys.exit(1)

    command = sys.argv[1]
    manager = ConfigManager()

    if command == "load":
        if len(sys.argv) != 3:
            print("用法: python config_manager.py load <文件路径>")
            sys.exit(1)
        config_data = manager.load_config(sys.argv[2])
        print(json.dumps(config_data, indent=2))
    elif command == "save":
        if len(sys.argv) != 4:
            print("用法: python config_manager.py save <源文件路径> <目标文件路径>")
            sys.exit(1)
        config_data = manager.load_config(sys.argv[2])
        manager.save_config(config_data, sys.argv[3])
    elif command == "load-all":
        if len(sys.argv) != 3:
            print("用法: python config_manager.py load-all <目录路径>")
            sys.exit(1)
        directory = sys.argv[2]
        all_configs = manager.load_all_configs(directory)
        for file_path, config_data in all_configs.items():
            print(f"文件: {file_path}")
            print(json.dumps(config_data, indent=2))
            print()
    else:
        print("无效的命令")
        sys.exit(1)
