#!/usr/bin/env python3
"""Translate finance-data.json to Korean using DeepSeek API and save as ko-finance-data.json"""
import json
import urllib.request
import urllib.error

# Load config
with open("/root/.openclaw/openclaw.json") as f:
    cfg = json.load(f)
API_KEY = cfg['models']['providers']['deepseek']['apiKey']
API_URL = "https://api.deepseek.com/v1/chat/completions"

# Load source data
with open("/data/news/json/finance-data.json", "r", encoding="utf-8") as f:
    finance_data = json.load(f)

# Build translation prompt
src_json = json.dumps(finance_data, ensure_ascii=False, indent=4)

system_prompt = """You are a professional financial translator specializing in Chinese to Korean translation.
Translate the JSON content from Chinese to Korean (한국어).

Rules:
1. Translate only the text values (names, descriptions, etc.) - do NOT translate numeric values, codes, percentage signs, plus/minus signs, or key names
2. Keep the JSON structure exactly the same
3. Output only valid JSON, no markdown, no explanation
4. For financial index names use standard Korean translations:
   - 上证指数 → 상해종합지수
   - 深证成指 → 선전성분지수
   - 恒生指数 → 항셍지수
   - prize → 현재가 (or keep as numeric label)
   - increase → 변동
   - ratio → 변동률
5. Keep the "finance_date" and "finance_asia_date" keys unchanged"""

user_prompt = f"""Translate this finance JSON to Korean, output valid JSON only:

{src_json}"""

payload = json.dumps({
    "model": "deepseek-chat",
    "messages": [
        {"role": "system", "content": system_prompt},
        {"role": "user", "content": user_prompt}
    ],
    "temperature": 0.1,
    "max_tokens": 2000,
    "stream": False
}).encode("utf-8")

req = urllib.request.Request(
    API_URL,
    data=payload,
    headers={
        "Content-Type": "application/json",
        "Authorization": f"Bearer {API_KEY}"
    }
)

try:
    resp = urllib.request.urlopen(req, timeout=60)
    result = json.loads(resp.read().decode("utf-8"))
    ko_text = result["choices"][0]["message"]["content"].strip()

    # Strip code fences if present
    if ko_text.startswith("```"):
        lines = ko_text.split("\n")
        ko_text = "\n".join(lines[1:])
        if ko_text.endswith("```"):
            ko_text = ko_text[:-3]
        ko_text = ko_text.strip()

    # Parse the translated JSON
    ko_data = json.loads(ko_text)

    # Save to file
    with open("/data/news/json/ko-finance-data.json", "w", encoding="utf-8") as f:
        json.dump(ko_data, f, ensure_ascii=False, indent=2)

    print("✅ Translation saved to /data/news/json/ko-finance-data.json")
    print("--- Content ---")
    print(json.dumps(ko_data, ensure_ascii=False, indent=2))
except urllib.error.HTTPError as e:
    print(f"HTTP Error: {e.code} - {e.read().decode('utf-8')}")
except Exception as e:
    print(f"Error: {e}")
    if 'result' in dir() and result:
        print("Raw response:", result)
