#!/usr/bin/env python
# -*- coding: utf-8 -*-
# time: 2024/4/11 9:07
# file: monitor.py
# author: David
# company: shenyang JY
import json
import os
import subprocess
from pathlib import Path

script_path = str(Path.cwd().resolve().parent.parent.parent / 'bin' / 'restart-forecast.sh')
config_folder = Path.cwd().resolve().parent


class Monitor(object):
    def __init__(self, logger, args):
        self.args = args
        self.logger = logger

    def update_config(self):
        files = list(config_folder.rglob("ModelCDQ_*"))
        files.sort(key=lambda x: (str(x)[str(x).index("ModelCDQ_")+9:-1]))
        if len(files) > 0:
            try:
                opt = vars(self.args.parse_args_and_yaml())
                file = files[-1]
                with open(file, 'r', encoding='utf-8') as f:
                    lines = f.readlines()  # 读取第一行参数
                    if "ModelCDQ" in lines[0].strip():
                        content = lines[0].strip()
                    else:
                        content = lines[1].strip()
                    content = eval(content[content.index("ModelCDQ")+11:])
                    content = content[0]['str']
                    update_opt = json.loads(content)
                    for key, value in update_opt.items():
                        opt[key] = value
                        print("key:", key, "value:", value)
                self.logger.info("下发配置文件，更新后的参数为：{}".format(opt))
                self.args.save_args_yml(opt, isdict=True)
                self.delete_file(files)
                if opt['reset_sys'] is True:
                    self.logger.info("-----重启超短期算法包-----")
                    subprocess.run(["sh", script_path])
            except Exception as e:
                self.logger.critical("超短期monitor任务出错：{}".format(e.args))
                self.delete_file(files)

    def delete_file(self, files):
        for filename in files:
            if os.path.exists(filename):
                os.remove(filename)
                self.logger.info(f"文件 {filename} 删除成功！")
            else:
                self.logger.info(f"文件 {filename} 不存在。")


if __name__ == '__main__':
    from config import myargparse
    from logs import Log

    args = myargparse(discription="场站端配置", add_help=False)
    log = Log()
    mo = Monitor(log.logger, args)
    mo.update_config()