#!/usr/bin/env python3
"""DeepSeek CLI 聊天工具 - 支持文件上下文 + 保留词 + 输出到文件"""
import json, sys, os, re

API_KEY = None
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"

history = [{"role": "system", "content": "You are a helpful assistant."}]

def chat(msg):
    history.append({"role": "user", "content": msg})
    payload = json.dumps({"model": "deepseek-chat", "messages": history, "temperature": 0.3, "max_tokens": 16384}).encode()
    import urllib.request
    req = urllib.request.Request(API_URL, data=payload, headers={'Content-Type': 'application/json', 'Authorization': f'Bearer {API_KEY}'})
    with urllib.request.urlopen(req, timeout=180) as r:
        resp = json.loads(r.read())['choices'][0]['message']['content']
    history.append({"role": "assistant", "content": resp})
    return resp

if __name__ == '__main__':
    file_path = None
    keep_file = None
    output_file = None
    keep_words = []

    args = sys.argv[1:]
    new_args = []
    i = 0
    while i < len(args):
        if args[i] == '--file' and i + 1 < len(args):
            file_path = args[i + 1]; i += 2
        elif args[i] == '--keep-file' and i + 1 < len(args):
            keep_file = args[i + 1]; i += 2
        elif args[i] == '--output' and i + 1 < len(args):
            output_file = args[i + 1]; i += 2
        else:
            new_args.append(args[i]); i += 1
    sys.argv = [sys.argv[0]] + new_args

    system_extra = ""
    if file_path:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        system_extra = f"\n\n유저가 제공한 파일 내용:\n```\n{content[:8000]}\n```"

    if keep_file:
        with open(keep_file, 'r', encoding='utf-8') as f:
            for line in f:
                word = line.strip()
                if word and not word.startswith('#'):
                    keep_words.append(word)
        if keep_words:
            system_extra += f"\n\n⚠️ 다음 단어는 고유명사/브랜드명으로, 반드시 원문을 유지하고 번역하지 마세요: {', '.join(keep_words[:80])}"

    if system_extra:
        history[0]["content"] += system_extra

    if len(sys.argv) > 1:
        result = chat(' '.join(sys.argv[1:]))
        # JSON 코드 블록 추출
        json_match = re.search(r'```(?:json)?\s*(\{.*?\}|\[.*?\])\s*```', result, re.DOTALL)
        if json_match:
            output = json_match.group(1)
        else:
            output = result
        
        if output_file:
            with open(output_file, 'w', encoding='utf-8') as f:
                # JSON 유효성 검사 후 저장
                try:
                    parsed = json.loads(output)
                    json.dump(parsed, f, ensure_ascii=False, indent=2)
                    print(f"✅ 저장 완료: {output_file}")
                except:
                    f.write(output)
                    print(f"⚠️ JSON 파싱 실패, 원문 저장: {output_file}")
        else:
            print(output)
    else:
        print("DeepSeek Chat (exit 입력 시 종료)\n")
        while True:
            try:
                msg = input(">>> ")
                if msg.lower() in ('exit', 'quit'): break
                print(chat(msg))
            except (EOFError, KeyboardInterrupt):
                break
            print()
