import json
import pandas as pd

def recomm_reason(filelist, note_review, printoutput=False):
    '''
    :param filelist: 投资组合guid的名称列表
    :param note_review: 投资组合的配置说明
    :param printoutput: 是否打印输出结果
    '''
    print('------------------------------------------------------------------------------------------')
    for file_name in filelist:
        # 读取原json文件
        try:
            with open(f'./json/{file_name}.json', 'r', encoding='utf-8') as file:
                data = json.load(file)
        except FileNotFoundError:
            print(f'{file_name}.json文件未找到，请检查文件路径。')
            continue
        except json.JSONDecodeError:
            print(f'{file_name}.json文件不是有效的 JSON 格式，请检查文件内容。')

        # 提取 note 字段中的 recomm_reason 内容
        import ast
        note_dict = ast.literal_eval(data[0]['data']['note'])

        # 更新 recomm_reason 内容
        data_date = data[0]['data']['data_date']
        try:
            new_reason = note_review[
                (note_review['rebalance_date'] == data_date) & (note_review['portfolio_guid'] == file_name)][
                'note_review'].iloc[0]
            note_dict['recomm_reason'] = new_reason
        except IndexError:
            print(f'{file_name}: rebalance_date or portfolio_guid does not match.')
            continue

        # 更新 note 字段
        data[0]['data']['note'] = json.dumps(note_dict, ensure_ascii=False)

        # 输出修改后的 JSON 数据，指定编码为 UTF - 8
        if printoutput: print(json.dumps(data, indent=2, ensure_ascii=False).encode('utf-8').decode())

        # 保存修改后的 JSON 数据到新文件
        try:
            with open(f'./json/{file_name}_{data_date}.json', 'w', encoding='utf-8') as file:
                json.dump(data, file, indent=2, ensure_ascii=False)
            print(f'修改后的 JSON 数据已成功保存到 [{file_name}_{data_date}.json] 文件中。')
        except Exception as e:
            print(f'保存文件时出现错误: {e}')
    print('------------------------------------------------------------------------------------------')


if __name__ == '__main__':
    # 參數設置
    filelist = [
        'AB088E61-FAB1-4466-B6AD-6E8AE253391E',
        '2CB50688-96F8-4C3E-87AB-6DEE2B4713B1',
        'D0FE0BF1-14F8-4350-833C-FD77AEE73E7A'
    ]
    note_review = pd.read_excel('./json/Outlook_Porfolio_2025_0602.xlsx', sheet_name='每月配置說明')
    # 更新說明
    recomm_reason = recomm_reason(filelist, note_review)