import subprocess
import time
import logging
from datetime import datetime
import pytz
from time import sleep

SESSION_NAME = "tunn"
COMMAND = "./backhaul -c config.toml"
MAX_ISSUES = 7
CHECK_INTERVAL = 5  # seconds
WARNING_TEXT = "[WARNING]"
ERROR_TEXT = "[ERROR]"

# Setup logging
logging.basicConfig(
    filename="tunn_monitor.log",
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S"
)

# Tehran time for display
def tehran_now_str():
    tz = pytz.timezone("Asia/Tehran")
    return datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")


def log_info(message):
    print(f"[{tehran_now_str()}] [INFO] {message}")
    logging.info(message)


def log_warning(message):
    print(f"[{tehran_now_str()}] [WARNING] {message}")
    logging.warning(message)


def log_error(message):
    print(f"[{tehran_now_str()}] [ERROR] {message}")
    logging.error(message)


def tmux_session_exists():
    result = subprocess.run(["tmux", "has-session", "-t", SESSION_NAME],
                            stdout=subprocess.DEVNULL,
                            stderr=subprocess.DEVNULL)
    return result.returncode == 0


def start_tmux_session():
    subprocess.run(["tmux", "kill-session", "-t", SESSION_NAME], stderr=subprocess.DEVNULL)
    sleep(5)
    subprocess.run(["tmux", "new-session", "-d", "-s", SESSION_NAME, COMMAND])
    log_info("Tmux session restarted.")


def get_issue_count():
    try:
        output = subprocess.check_output(["tmux", "capture-pane", "-pt", SESSION_NAME, "-S", "-100"])
        lines = output.decode(errors="ignore").splitlines()
        warning_count = sum(1 for line in lines if WARNING_TEXT in line)
        error_count = sum(1 for line in lines if ERROR_TEXT in line)
        total_issues = warning_count + error_count
        log_info(f"Detected {warning_count} warnings and {error_count} errors in tmux output.")
        return total_issues
    except Exception as e:
        log_error(f"Failed to read tmux pane: {e}")
        return 0


def main_loop():
    if not tmux_session_exists():
        log_info("Tmux session not found. Starting new session...")
        start_tmux_session()
    else:
        log_info("Tmux session already running.")

    while True:
        if not tmux_session_exists():
            log_warning("Tmux session missing. Restarting...")
            start_tmux_session()

        if get_issue_count() >= MAX_ISSUES:
            log_warning("Too many issues detected (warnings/errors). Restarting tmux session...")
            start_tmux_session()

        time.sleep(CHECK_INTERVAL)


if __name__ == "__main__":
    main_loop()
