import pygame
import requests
import hashlib
import random
import json

# ================= 百度翻译 =================
APP_ID = "你的APP_ID"
SECRET_KEY = "你的SECRET_KEY"
API_URL = "https://fanyi-api.baidu.com/api/trans/vip/translate"

def translate(text, f, t):
    salt = str(random.randint(32768, 65536))
    sign = hashlib.md5((APP_ID + text + salt + SECRET_KEY).encode()).hexdigest()
    params = {
        "q": text, "from": f, "to": t,
        "appid": APP_ID, "salt": salt, "sign": sign
    }
    try:
        res = requests.get(API_URL, params=params, timeout=5)
        return json.loads(res.text)["trans_result"][0]["dst"]
    except:
        return "fail"

# ================= pygame =================
pygame.init()
WIDTH, HEIGHT = 640, 520
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("translator")
font = pygame.font.SysFont("simhei", 18)
clock = pygame.time.Clock()

input_text = ""
output_text = ""
to_english = True
history = []
scroll_y = 0

# 按钮
class Btn:
    def __init__(self, x, y, w, h, text):
        self.rect = pygame.Rect(x, y, w, h)
        self.text = text
    def draw(self, color=(80, 130, 200)):
        pygame.draw.rect(screen, color, self.rect)
        screen.blit(font.render(self.text, True, (255,255,255)), (self.rect.x+6, self.rect.y+5))
    def hit(self, pos):
        return self.rect.collidepoint(pos)

trans_btn = Btn(30, 55, 80, 30, "go")
clear_btn = Btn(120, 55, 80, 30, "clear")
switch_btn = Btn(210, 55, 110, 30, "zh->en")
clear_hist_btn = Btn(460, 55, 140, 30, "clear history")

# 键盘
KEYS = ["qwertyuiop", "asdfghjkl", "zxcvbnm"]
key_btns = []
for r, row in enumerate(KEYS):
    for c, ch in enumerate(row):
        key_btns.append(Btn(30 + c*48, 310 + r*38, 44, 32, ch))

key_btns.append(Btn(496, 386, 60, 32, "<-"))
key_btns.append(Btn(220, 386, 256, 32, "space"))

# ================= main loop =================
running = True
while running:
    screen.fill((245, 245, 245))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        
            p = pygame.mouse.get_pos()

            if trans_btn.hit(p):
                f, t = ("zh","en") if to_english else ("en","zh")
                output_text = translate(input_text, f, t)
                history.append((input_text, output_text))

            elif clear_btn.hit(p):
                input_text = ""; output_text = ""

            elif switch_btn.hit(p):
                to_english = not to_english
                switch_btn.text = "zh->en" if to_english else "en->zh"

            elif clear_hist_btn.hit(p):
                history.clear()

            for b in key_btns:
                if b.hit(p):
                    if b.text == "<-": input_text = input_text[:-1]
                    elif b.text == "space": input_text += " "
                    else: input_text += b.text

            # 点击历史记录
            for i, (x, y, w, h) in enumerate(history_rects):
                if pygame.Rect(x, y, w, h).collidepoint(p):
                    input_text = history[i][0]


            scroll_y += event.y * 20

    # 输入框
    pygame.draw.rect(screen, (255,255,255), (30, 12, 580, 30), 1)
    screen.blit(font.render(input_text, True, (0,0,0)), (35, 16))

    # 功能按钮
    trans_btn.draw()
    clear_btn.draw()
    switch_btn.draw()
    clear_hist_btn.draw((180, 80, 80))

    # 输出框
    pygame.draw.rect(screen, (255,255,255), (30, 100, 580, 50), 1)
    screen.blit(font.render(output_text, True, (0,0,180)), (35, 108))

    # 历史记录区域
    screen.blit(font.render("history", True, (100,100,100)), (30, 170))
    hist_area = pygame.Rect(30, 195, 580, 105)
    pygame.draw.rect(screen, (255,255,255), hist_area, 1)

    history_rects = []
    clip = screen.get_clip()
    screen.set_clip(hist_area)

    start_y = 200 + scroll_y
    for i, (src, dst) in enumerate(history):
        y = start_y + i * 22
        txt = font.render(f"{src} -> {dst}", True, (50, 50, 50))
        screen.blit(txt, (35, y))
        history_rects.append((35, y, txt.get_width(), 20))

    screen.set_clip(clip)

    # 键盘
    for b in key_btns:
        b.draw((160, 160, 160))

    pygame.display.flip()
    clock.tick(30)

pygame.quit()