import requests
import time
import base64

def test_translate_image_api(image_url, use_celery=False):
    url = "http://cckb9998.synology.me:8001/translate_image/"
    payload = {
        "image_url": image_url,
        "use_celery": use_celery
    }
    try:
        response = requests.post(url, json=payload)
        if response.status_code == 200:
            print(f"Request successful: {response.json()}")
            return response.json()
        else:
            print(f"Error: {response.status_code}, {response.text}")
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")

def check_task_status(task_id):
    url = f"http://cckb9998.synology.me:8001/task_status/{task_id}"
    try:
        response = requests.get(url)
        if response.status_code == 200:
            result = response.json()
            print(f"Task status: {result}")
            if result.get("status") == "Success" and "result" in result:
                # 번역된 이미지를 base64로 받아 로컬에 저장
                save_image(result["result"], f"translated_image_{task_id}.png")
        else:
            print(f"Error: {response.status_code}, {response.text}")
    except requests.exceptions.RequestException as e:
        print(f"Request failed: {e}")

def save_image(image_base64, file_name):
    try:
        # base64 디코딩하여 이미지 저장
        image_data = base64.b64decode(image_base64)
        with open(file_name, "wb") as file:
            file.write(image_data)
        print(f"Image saved successfully as {file_name}")
    except Exception as e:
        print(f"Failed to save image: {e}")

if __name__ == "__main__":

    # 테스트할 이미지 URL
    image_url = "https://file.percenty.co.kr/public/652bed8e865b1f32ea62bf1f/products/66f7489b86608659ad011faf/0fbf1050-0a49-4c37-83b5-6279b66d6e48.jpg"

    # API 호출
    result = test_translate_image_api(image_url, use_celery=True)

    # 작업 ID가 있는 경우 상태를 조회
    if result and "task_id" in result:
        task_id = result["task_id"]

        # 상태 확인을 위한 대기
        time.sleep(5)  # Celery 작업이 끝나기를 잠시 대기

        # 작업 상태 확인
        check_task_status(task_id)
