# =============== #
# UTILS FUNCTIONS #
# =============== #
import datetime
import os
import shlex
import subprocess
import sys
from typing import List
import logging

from .consts import FOLDER_CMD_OUTPUTS, FOLDERS_NETWORK_LEVEL, FILES_NETWORK_LEVEL

logger = logging.getLogger()
logging.basicConfig(level=logging.INFO)


def run_cmd(command: List[str]):
    # Generate a unique filename based on the current timestamp
    timestamp = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
    cmd_name = command[0]
    cmd_str = shlex.join(command)
    output_file = os.path.join(FOLDER_CMD_OUTPUTS, f"output_{timestamp}_{cmd_name}.txt")

    logger.info(f"Running command: {cmd_str}")
    logger.info(f"Outpute: {output_file}")

    with open(output_file, "w") as f:
        f.write(cmd_str)
        f.write("\n")
        f.flush()
        result = subprocess.run(command, stdout=f, stderr=f)

    return {"result": result, "output": output_file}


def check_mission_structure_initiated():
    for path in [*FOLDERS_NETWORK_LEVEL, *FILES_NETWORK_LEVEL]:
        if not os.path.exists(path):
            raise ValueError(f"path {path} don't exists")


def check_running_with_root():
    if os.geteuid() != 0:
        print("Error: This script requires sudo permissions.")
        sys.exit(1)


def read_file_as_list(filepath: str) -> List[str]:
    l = []
    with open(filepath) as f:
        for e in f:
            e = e.strip()
            if not e:
                continue
            l.append(e)
    return l


def write_file_from_list(file: str, l: List[str]) -> None:
    with open(file, "w") as f:
        for e in l:
            f.write(e)
            f.write("\n")


def run_cmd_then_print(command):
    results = run_cmd(command)
    with open(results["output"]) as f:
        print(f.read())
    logger.info(f"Output: {results['output']}")
