#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
翻訳アプリ
  - Tkinter で UI を構築
  - ollama ライブラリでローカル LLM (translategemma:12b) を呼び出し
  - 英語 ↔ 日本語の 2 方向翻訳
"""

import tkinter as tk
from tkinter import ttk, messagebox
import ollama  # pip install ollama

# ---------- 1. 翻訳ロジック ----------
PROMPT_TEMPLATE = (
  "You are a professional {SOURCE_LANG} ({SOURCE_CODE}) to {TARGET_LANG} ({TARGET_CODE}) translator. "
  "Your goal is to accurately convey the meaning and nuances of the original {SOURCE_LANG} text "
  "while adhering to {TARGET_LANG} grammar, vocabulary, and cultural sensitivities.\n"
  "Produce only the {TARGET_LANG} translation, without any additional explanations or commentary. "
  "Please translate the following {SOURCE_LANG} text into {TARGET_LANG}:\n\n{TEXT}"
)

def translate_text(source_lang: str, source_code: str,
                   target_lang: str, target_code: str,
                   text: str) -> str:
  """
  ollama の translategemma モデルにプロンプトを投げて翻訳結果を取得。
  """
  if not text.strip():
    raise ValueError("翻訳対象のテキストが空です。")

  prompt = PROMPT_TEMPLATE.format(
    SOURCE_LANG=source_lang,
    SOURCE_CODE=source_code,
    TARGET_LANG=target_lang,
    TARGET_CODE=target_code,
    TEXT=text
  )

  # ollama.chat の呼び出し (モデルが起動している必要あり)
  try:
    response = ollama.chat(
      model="translategemma:12b",
      messages=[{"role": "user", "content": prompt}]
    )
  except Exception as e:
    raise RuntimeError(f"LLM 呼び出しエラー: {e}")

  # ollama のレスポンス形式は {'message': {'content': '...'}} である想定
  translated = response.get("message", {}).get("content", "")
  if not translated.strip():
    raise RuntimeError("LLM から有効な翻訳結果が返ってきませんでした。")
  return translated.strip()

# ---------- 2. GUI ----------
class TranslatorApp(tk.Tk):
  def __init__(self):
    super().__init__()
    self.title("ローカル LLM 翻訳アプリ")
    self.geometry("900x500")
    self.resizable(False, False)

    # フレーム分割 (左: 原文, 右: 翻訳文)
    left_frame = ttk.Frame(self, padding=10)
    right_frame = ttk.Frame(self, padding=10)
    left_frame.grid(row=0, column=0, sticky="nsew")
    right_frame.grid(row=0, column=1, sticky="nsew")

    # 原文テキストボックス
    ttk.Label(left_frame, text="原文", 
              font=("Arial", 12, "bold")).pack(anchor="w")
    self.source_text = tk.Text(left_frame, wrap="word", width=50, height=20)
    self.source_text.pack(fill="both", expand=True)

    # 翻訳文テキストボックス
    ttk.Label(right_frame, text="翻訳文", 
              font=("Arial", 12, "bold")).pack(anchor="w")
    self.target_text = tk.Text(right_frame, wrap="word", width=50, height=20)
    self.target_text.pack(fill="both", expand=True)

    # ボタン群
    btn_frame = ttk.Frame(self, padding=10)
    btn_frame.grid(row=1, column=0, columnspan=2, sticky="ew")

    ttk.Button(btn_frame, 
               text="ペースト", 
               command=self.paste_source).grid(row=0, column=0, padx=5, pady=5)
    ttk.Button(btn_frame, 
               text="コピー", 
               command=self.copy_target).grid(row=0, column=1, padx=5, pady=5)
    ttk.Button(btn_frame, 
      text="英語→日本語に翻訳", 
      command=self.translate_en_to_ja).grid(row=0, column=2, padx=5, pady=5)
    ttk.Button(btn_frame, 
      text="日本語→英語に翻訳", 
      command=self.translate_ja_to_en).grid(row=0, column=3, padx=5, pady=5)

  # ---------- 3. イベントハンドラ ----------
  def paste_source(self):
    try:
      clip_text = self.clipboard_get()
      self.source_text.delete("1.0", tk.END)
      self.source_text.insert(tk.END, clip_text)
    except tk.TclError:
      messagebox.showwarning("クリップボード", 
                             "クリップボードにテキストがありません。")

  def copy_target(self):
    content = self.target_text.get("1.0", tk.END).strip()
    if content:
      self.clipboard_clear()
      self.clipboard_append(content)
      messagebox.showinfo("コピー", "翻訳文をクリップボードへコピーしました。")
    else:
      messagebox.showwarning("コピー", "コピーする内容がありません。")

  def translate_en_to_ja(self):
    text = self.source_text.get("1.0", tk.END).strip()
    if not text:
      messagebox.showwarning("翻訳", "原文が空です。")
      return
    self.target_text.delete("1.0", tk.END)
    self.target_text.insert(tk.END, "翻訳中…")
    self.update_idletasks()
    try:
      result = translate_text(
        source_lang="English",
        source_code="en",
        target_lang="Japanese",
        target_code="ja",
        text=text
      )
      self.target_text.delete("1.0", tk.END)
      self.target_text.insert(tk.END, result)
    except Exception as e:
      self.target_text.delete("1.0", tk.END)
      messagebox.showerror("翻訳エラー", str(e))

  def translate_ja_to_en(self):
    text = self.source_text.get("1.0", tk.END).strip()
    if not text:
      messagebox.showwarning("翻訳", "原文が空です。")
      return
    self.target_text.delete("1.0", tk.END)
    self.target_text.insert(tk.END, "翻訳中…")
    self.update_idletasks()
    try:
      result = translate_text(
        source_lang="Japanese",
        source_code="ja",
        target_lang="English",
        target_code="en",
        text=text
      )
      self.target_text.delete("1.0", tk.END)
      self.target_text.insert(tk.END, result)
    except Exception as e:
      self.target_text.delete("1.0", tk.END)
      messagebox.showerror("翻訳エラー", str(e))

# ---------- 4. エントリポイント ----------
if __name__ == "__main__":
  app = TranslatorApp()
  app.mainloop()
