#!/usr/bin/env python3
# Debugger module for the Fenrir screen reader.

import os
import pathlib
from datetime import datetime

from fenrirscreenreader.core import debug


class DebugManager:
    def __init__(self, file_name=""):
        self._file = None
        self._fileOpened = False
        self._fileName = (
            "/tmp/fenrir_"
            + str(os.getpid())
            + "_"
            + str(datetime.utcnow().strftime("%Y-%m-%d_%H-%M-%S"))
            + ".log"
        )
        if file_name != "":
            self._fileName = file_name

    def initialize(self, environment):
        self.env = environment

    def shutdown(self):
        self.close_debug_file()

    def __del__(self):
        try:
            self.shutdown()
        except Exception as e:
            # Cannot use debug manager to log its own shutdown errors
            print(f"DebugManager shutdown: Error during shutdown: {e}")

    def open_debug_file(self, file_name=""):
        self._fileOpened = False
        if file_name != "":
            self._fileName = file_name
        if self._fileName != "":
            directory = os.path.dirname(self._fileName)
            if not os.path.exists(directory):
                pathlib.Path(directory).mkdir(parents=True, exist_ok=True)
            try:
                self._file = open(self._fileName, "a")
                # Set readable permissions for all users (644)
                os.chmod(self._fileName, 0o644)
                self._fileOpened = True
            except Exception as e:
                print(e)

    def write_debug_out(
        self, text, level=debug.DebugLevel.DEACTIVE, on_any_level=False
    ):

        mode = self.env["runtime"]["SettingsManager"].get_setting(
            "general", "debug_mode"
        )
        if mode == "":
            mode = "FILE"
        mode = mode.upper().split(",")
        file_mode = "FILE" in mode
        print_mode = "PRINT" in mode

        if (
            int(
                self.env["runtime"]["SettingsManager"].get_setting_as_int(
                    "general", "debug_level"
                )
            )
            < int(level)
        ) and not (
            on_any_level
            and int(
                self.env["runtime"]["SettingsManager"].get_setting_as_int(
                    "general", "debug_level"
                )
            )
            > int(debug.DebugLevel.DEACTIVE)
        ):
            if self._fileOpened:
                self.close_debug_file()
            return
        else:
            if not self._fileOpened and file_mode:
                self.open_debug_file()
            timestamp = str(datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f"))
            if on_any_level:
                level_info = "INFO ANY"
            else:
                level_info = str(level)

            # Changed order: text comes first, then level and timestamp
            msg = text + " - " + level_info + " " + timestamp

            if print_mode:
                print(msg)
            if file_mode:
                try:
                    self._file.write(msg + "\n")
                except Exception as e:
                    print(e)

    def close_debug_file(self):
        if not self._fileOpened:
            return False
        if self._file is not None:
            try:
                self._file.close()
            except Exception as e:
                print(e)
        self._fileOpened = False
        return True

    def get_debug_file(self):
        return self._fileName

    def set_debug_file(self, file_name):
        self.close_debug_file()
        self._fileName = file_name
