import os
from pathlib import Path
import sys

os.environ["FLAGS_enable_pir_api"] = "0"
os.environ["FLAGS_use_onednn"] = "0"
os.environ["FLAGS_use_mkldnn"] = "0"
os.environ["FLAGS_use_onednn_bfloat16"] = "0"
os.environ["ONEDNN_VERBOSE"] = "0"

SRC_DIR = Path(__file__).resolve().parents[1]
if str(SRC_DIR) not in sys.path:
    sys.path.insert(0, str(SRC_DIR))

from osc.gateway import VrcOscGateway
from discord_control.actions import setDiscordMute
from ocr.ocr_actions import runOcrFromScreen
from translate.translate_actions import saveTranslationText
from translate.translate_actions import translateTextToJapanese
from vrc_log.log_actions import collectVrchatLog
from vrc_log.log_actions import startSelfMonitor
from vrc_log.log_actions import startVrcLogMonitor
from vrc_log.log_actions import stopSelfMonitor
from vrc_log.log_actions import stopVrcLogMonitor

PARAM_DISCORD_MUTE = "DiscordSend"
PARAM_LOG_GREP = "vrc_log"
PARAM_OCR = "ocrEnabled"
PARAM_TRANSLATE_OCR = "translation"


def create_gateway():
    gateway = VrcOscGateway(host="127.0.0.1", port=9001)

    def on_discord_mute(address, *args):
        if not args:
            gateway.log("ERROR", "DiscordSend args empty")
            return

        if gateway.is_rising_edge(address, args[0]):
            gateway.log("INFO", f"received {address} args={args}")
            setDiscordMute()

    vrc_log_enabled = False
    def on_log_grep(address, *args):
        nonlocal vrc_log_enabled

        if not args:
            gateway.log("ERROR", "vrc_log args empty")
            return

        if gateway.is_rising_edge(address, args[0]):
            vrc_log_enabled = not vrc_log_enabled
            gateway.log("INFO", f"received {address} args={args} enabled={vrc_log_enabled}")

            if vrc_log_enabled:
                collectVrchatLog(notify_changed=True)
                startVrcLogMonitor()
            else:
                stopVrcLogMonitor()

    def on_ocr(address, *args):
        if not args:
            gateway.log("ERROR", "ocrEnabled args empty")
            return

        if gateway.is_rising_edge(address, args[0]):
            gateway.log("INFO", f"received {address} args={args}")
            runOcrFromScreen()

    def on_translate_ocr(address, *args):
        if not args:
            gateway.log("ERROR", "translateOcr args empty")
            return

        if gateway.is_rising_edge(address, args[0]):
            gateway.log("INFO", f"received {address} args={args}")

            result = runOcrFromScreen()
            if not result:
                gateway.log("ERROR", "OCR result is None")
                return

            text = result.get("text", "")
            if not text.strip():
                gateway.log("INFO", "OCR text is empty. translation skipped")
                return

            translated = translateTextToJapanese(text)
            if not translated.strip():
                gateway.log("INFO", "translation result is empty")
                return

            image_path = result.get("image_path")
            stem = image_path.stem if image_path else "translation"
            saved = saveTranslationText(stem, translated)
            gateway.log("INFO", f"translation saved={saved}")

    gateway.map(PARAM_DISCORD_MUTE, on_discord_mute)
    gateway.map(PARAM_LOG_GREP, on_log_grep)
    gateway.map(PARAM_OCR, on_ocr)
    gateway.map(PARAM_TRANSLATE_OCR, on_translate_ocr)
    gateway.set_default_debug(enabled=False)
    return gateway


def main():
    gateway = create_gateway()
    startSelfMonitor()
    gateway.serve_forever()


if __name__ == "__main__":
    main()
