from datetime import datetime
import re

import pyperclip
from deep_translator import GoogleTranslator

from common.runtime_log import appendRuntimeLog

IGNORE_EXACT = {
    "戻る",
    "翻訳",
    "OCR",
    "VRCLOG",
    "Discord_Mute",
    "Screenshot",
    "OCR_Toggle",
    "DCR_Toggle",
    "HI",
}


def log(level, message):
    now = datetime.now().strftime("%H:%M:%S")
    print(f"[{level}] {now} {message}", flush=True)


def saveTranslationText(stem, text):
    return appendRuntimeLog(
        "TRANSLATION TEXT",
        f"source={stem}\n{text}",
    )


def looksLikeNoise(line):
    value = line.strip()
    if not value:
        return True
    if value in IGNORE_EXACT:
        return True
    if len(value) <= 2:
        return True
    if "_" in value:
        return True
    if re.fullmatch(r"[A-Za-z0-9\-_/]+", value):
        return True
    return False


def normalizeSourceText(text):
    lines = []

    for raw_line in text.splitlines():
        line = raw_line.strip()
        if looksLikeNoise(line):
            continue
        lines.append(line)

    unique_lines = []
    seen = set()
    for line in lines:
        if line not in seen:
            unique_lines.append(line)
            seen.add(line)

    return "\n".join(unique_lines).strip()


def translateTextToJapanese(text):
    source = normalizeSourceText(text)
    if not source:
        log("INFO", "翻訳対象が空です")
        return ""

    log("CHECK", "Translation source")
    for line in source.splitlines():
        print(line, flush=True)

    try:
        translated = GoogleTranslator(
            source="auto",
            target="ja",
        ).translate(source)
    except Exception as e:
        log("ERROR", f"translation failed detail={e}")
        return ""

    translated = translated.strip()
    if not translated:
        log("INFO", "翻訳結果は空です")
        return ""

    try:
        pyperclip.copy(translated)
        log("INFO", "翻訳結果をクリップボードへコピーしました")
    except Exception as e:
        log("ERROR", f"clipboard copy failed detail={e}")

    log("CHECK", "Translation result")
    for line in translated.splitlines():
        print(line, flush=True)

    return translated
