# -*- coding: utf-8 -*-
import glob
import os
import sys
import datetime

sys.path.append(os.path.join(os.path.abspath(__file__).split('AlphaGenerator')[0] + 'AlphaGenerator'))
PROJECT_PATH = os.path.join(os.path.abspath(__file__).split('AlphaGenerator')[0] + 'AlphaGenerator')


def get_today_date():
    d = datetime.datetime.now().strftime('%Y-%m-%d')
    today = {
        'year': d.split('-')[0],
        'month': d.split('-')[1],
        'day': d.split('-')[2]
    }
    return today


def now_files(today):
    create_new_file_path = os.path.join(PROJECT_PATH, 'merge_today_alphas', today['year'], today['month'], today['day'])

    os.makedirs(create_new_file_path, exist_ok=True)

    return create_new_file_path


def load_today_alphas(today_generated_alphas_path):
    today_generated_alphas = []
    print(f"读取路径: {today_generated_alphas_path}")

    # 检查路径是否存在
    if not os.path.exists(today_generated_alphas_path):
        print(f"警告: 路径不存在 {today_generated_alphas_path}")
        return today_generated_alphas

    print(f"读取路径: {today_generated_alphas_path}")

    # 检查路径是否存在
    if not os.path.exists(today_generated_alphas_path):
        print(f"警告: 路径不存在 {today_generated_alphas_path}")
        return today_generated_alphas

    # 获取所有txt文件
    txt_files = glob.glob(os.path.join(today_generated_alphas_path, "*.txt"))

    if not txt_files:
        print(f"提示: 未找到txt文件在 {today_generated_alphas_path}")
        return today_generated_alphas

    print(f"找到 {len(txt_files)} 个txt文件")

    # 读取所有txt文件内容
    for txt_file in txt_files:
        try:
            with open(txt_file, 'r', encoding='utf-8') as f:
                content = f.read().strip()
                if content:
                    save_alphas = content.split('\n')
                    for save_alpha in save_alphas:
                        if save_alpha:
                            today_generated_alphas.append(save_alpha)
                    print(f"已读取: {os.path.basename(txt_file)}")
        except Exception as e:
            print(f"读取文件失败 {txt_file}: {e}")

    today_generated_alphas = list(set(today_generated_alphas))
    print(f"成功加载 {len(today_generated_alphas)} 个alpha代码")
    return today_generated_alphas


def save_today_alphas(now_files_path, alphas, today):
    # 生成年月日时分秒
    now_time = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
    print(now_time)
    save_file_name = f'merge_alphas_{now_time}.txt'

    # 保存到指定路径
    with open(os.path.join(now_files_path, save_file_name), 'w', encoding='utf-8') as f:
        for alpha in alphas:
            f.write(alpha + '\n\n')
    print(f"已保存 {len(alphas)} 个alpha代码到 {save_file_name}")


def main():
    today = get_today_date()
    today_generated_alphas_path = os.path.join(PROJECT_PATH, 'generated_alpha', today['year'], today['month'], today['day'])
    alphas = load_today_alphas(today_generated_alphas_path)
    if not alphas:
        print("没有alpha代码需要保存")
        return

    now_files_path = now_files(today)

    save_today_alphas(now_files_path, alphas, today)


if __name__ == '__main__':
    main()
