#keyが入れ子になっている階層型の辞書型変数infがあります。
#階層構造になっているkeyをseparator = ':' で接続して
#１つのkeyにしたフラットな辞書型変数replace_dictを作る関数を作り、
#replace_dictdで置換する関数を独自実装して
#template.txtを置換して保存するpythonスクリプト

import os
import re

# 階層型辞書
inf = {
    "network": {
        "device_name": "router-01",
        "interface": {
            "GigabitEthernet1/0": {
                "ip_address": "192.168.1.1",
                "subnet_mask": "255.255.255.0"
            },
            "GigabitEthernet2/0": {
                "ip_address": "10.0.0.1",
                "subnet_mask": "255.255.255.0"
            }
        }
    },
    "location": "Tokyo",
    "version": "1.2.3"
}

def flatten_dict(d, parent_key='', sep=':'):
    """
    階層的な辞書をフラットな辞書に変換する関数。
    """
    items = {}
    for k, v in d.items():
        new_key = f"{parent_key}{sep}{k}" if parent_key else k
        if isinstance(v, dict):
            items.update(flatten_dict(v, new_key, sep=sep))
        else:
            items[new_key] = v
    return items

def replace_template(template_content, replace_dict, force_replace = False):
    """
    テンプレート文字列内の {{key}} を辞書の値で置換する関数。
    存在しないキーは空白に置換します。
    """
    # テンプレート内の {{...}} のすべてのキーを抽出
    keys_in_template = re.findall(r"\{\{\s*(.*?)\s*\}\}", template_content)
    
    # 抽出したキーを一つずつ処理
    for key in set(keys_in_template):
        # 辞書にキーが存在するか確認
        if key in replace_dict:
            # 存在する場合は値で置換
            value = str(replace_dict[key])
        else:
            # 存在しない場合
            if force_replace:
                value = ""
            else:
                value = None

        # 正規表現パターンを作成して置換を実行
        if value is not None:
            pattern = r"\{\{\s*" + re.escape(key) + r"\s*\}\}"
            template_content = re.sub(pattern, value, template_content)
        
    return template_content

# --- メイン処理 ---

# 階層型辞書をフラットな辞書に変換
# この関数では、キーに / や . などの特殊文字が含まれていても問題ありません。
replace_dict = flatten_dict(inf)

# テンプレートファイルのパス
template_file = 'template.txt'
output_file = 'output.txt'

# テンプレートファイルの読み込み
try:
    with open(template_file, 'r', encoding='utf-8') as f:
        template_content = f.read()
except FileNotFoundError:
    print(f"エラー: '{template_file}' が見つかりません。")
    exit()

# テンプレートの置換を実行
rendered_template = replace_template(template_content, replace_dict, force_replace = True)

# 結果をファイルに保存
with open(output_file, 'w', encoding='utf-8') as f:
    f.write(rendered_template)

print("テンプレートの置換が完了しました。")
print(f"結果は '{output_file}' に保存されました。")