
import json
import os

class CodeTranslator:
    def __init__(self):
        self.maps = {}

    def load_concept_maps(self, path):
        if os.path.isdir(path):
            for filename in os.listdir(path):
                if filename.endswith('.json'):
                    self._load_map_file(os.path.join(path, filename))
        else:
            self._load_map_file(path)

    def _load_map_file(self, filepath):
        with open(filepath, 'r') as f:
            concept_map = json.load(f)
            self._parse_concept_map(concept_map)

    def _parse_concept_map(self, concept_map):
        if 'group' in concept_map:
            for group in concept_map['group']:
                source_system = group.get('source')
                target_system = group.get('target')
                if source_system and target_system:
                    if source_system not in self.maps:
                        self.maps[source_system] = {}
                    if target_system not in self.maps[source_system]:
                        self.maps[source_system][target_system] = {}
                    for element in group.get('element', []):
                        source_code = element.get('code')
                        if 'target' in element:
                            for target in element['target']:
                                target_code = target.get('code')
                                if source_code and target_code:
                                    self.maps[source_system][target_system][source_code] = target_code

    def translate(self, system, code):
        if system in self.maps:
            for target_system in self.maps[system]:
                if code in self.maps[system][target_system]:
                    return self.maps[system][target_system][code]
        return None
