import os
import psutil
import json
import shutil
import datetime
import subprocess

current_dir = os.path.dirname(os.path.abspath(__file__))
weshop_native_dir = os.path.join(current_dir, "..")
actual_bin_dir = current_dir
resources_dir = os.path.join(weshop_native_dir, "resources")
bin_dir = resources_dir
log_dir = os.path.join(weshop_native_dir, "logs")
err_dir = os.path.join(resources_dir, "err")
python_exe = os.path.join(resources_dir, "python","python.exe")
pid_json = os.path.join(actual_bin_dir, "pid.json")
electron_status_file = os.path.join(weshop_native_dir, "logs", "status.log")

def terminate_process_by_pid(pid):
    try:
        process = psutil.Process(pid)
        process.terminate()
        print(f"Process with PID {pid} terminated successfully.")
    except psutil.NoSuchProcess:
        print(f"No process found with PID {pid}.")
    except psutil.AccessDenied:
        print(f"Access denied to terminate process with PID {pid}.")

def terminate_processes(pids):
    for pid in pids:
        try:
            parent_process = psutil.Process(pid)
            child_processes = parent_process.children(recursive=True)
            
            # Terminate child processes
            for child in child_processes:
                child.terminate()
                print(f"Terminated process {pid}'s subprocess {child.pid}")
                
            # Wait for child processes to terminate
            psutil.wait_procs(child_processes)

            # Terminate the parent process
            parent_process.terminate()
            
            print(f"Terminated process {pid} and its child processes.")
        
        except psutil.NoSuchProcess:
            print(f"No such process with PID {pid}.")

class ConfigReader():
    def __init__(self) -> None:
        self.config_path = os.path.join(actual_bin_dir, "config.json")
        with open(self.config_path, "r") as config_file:
            config_data = json.load(config_file)
        self.log_mode = config_data["log_mode"]
        self.config_data = config_data
    def write(self, key, value):
        with open(self.config_path, "r") as config_file:
            config_data = json.load(config_file)
        config_data[key] = value
        with open(self.config_path, "w") as config_file:
            json.dump(config_data, config_file)


configReader = ConfigReader()


if __name__ == "__main__":
    with open(electron_status_file, "w") as log:
        print("weshop native status code: 3001", file=log, flush=True)

    if "boot_time" not in configReader.config_data:
        pass
    else:
        current_boot_time = psutil.boot_time()
        if current_boot_time != configReader.config_data["boot_time"]:
            with open(electron_status_file, "w") as electron_status:
                electron_status.truncate(0)  
        else:
            with open(pid_json, "r") as file:
                json_data = json.load(file)
                pid_list = json_data["pid"]
                terminate_processes(pid_list) 
            
            with open(electron_status_file, "w") as electron_status:
                electron_status.truncate(0)

    with open(pid_json, "r") as file:
        json_data = json.load(file)
        pid_list = json_data["pid"]
        terminate_processes(pid_list) 
    with open(electron_status_file, "w") as electron_status:
        electron_status.truncate(0)

    with open(pid_json, "w") as file:
        json.dump({"pid":[]},file)

    # 之前的杀不死都是nginx自动重启了
    port_num_json_path = os.path.join(actual_bin_dir, "port_num.json")
    with open(port_num_json_path, "r") as json_file:
        json_data = json.load(json_file)
    port = json_data["port_num"]
    
    command = f"netstat -ano | findstr :{port}"
    result = subprocess.run(command, capture_output=True, text=True, shell=True)

    # Extract the PID volume list from the command output
    output_lines = result.stdout.strip().split("\n")
    # print(output_lines)
    pid_volume_list = [line.split()[-1] for line in output_lines]
    # print([line.split() for line in output_lines if line[1].endswith(f":{port}")])
    nginx_pid = []
    for line in output_lines:
        if line.split()[1].endswith(f":{port}"):
            nginx_pid.append(int(line.split()[-1]))
    nginx_pid = list(set(nginx_pid))
    print(f"pid list is {nginx_pid}")
    for pid in nginx_pid:
        terminate_process_by_pid(pid)

    current_datetime = datetime.datetime.now()
    formatted_time = current_datetime.strftime("%Y_%m_%d_%H_%M_%S")
    backup_path = os.path.join(log_dir, f"logs_backup_{formatted_time}")
    os.mkdir(backup_path)
    for file in os.listdir(log_dir):
        if os.path.isfile(os.path.join(log_dir, file)):
            shutil.copy(os.path.join(log_dir, file), os.path.join(backup_path, file))
            # 备份后删除了吧
            if file == "backend.log" or file == "scheduler.log" or file == "broker.log" or file == "sidecar.log" or file == "frontend.log":
                file_path = os.path.join(log_dir, file)
                with open(file_path, "w") as file:
                    file.truncate(0)
            
    now = datetime.datetime.now()

    # Calculate the threshold date (one week ago)
    threshold_date = now - datetime.timedelta(days=7)
    for item in os.scandir(log_dir):
        if item.is_dir():
            creation_time = datetime.datetime.fromtimestamp(item.stat().st_ctime)
            if creation_time < threshold_date:
                # Delete the subfolder and its contents recursively
                os.system(f"rm -rf {item.path}")
                
    # with open(electron_status_file, "w") as electron_status:
    #     print("weshop native status code: 2001", file = electron_status, flush= True)
    
    # os.remove(os.path.join(log_dir, "start.log"))

    with open(os.path.join(log_dir, "start.log"), "w") as log:
        print("程序已终止", file=log, flush=True)
        log.truncate(0)
