# 用 DeepSeek API 写一个命令行 AI 助手——支持多轮对话，输入 quit 退出，
# API Key 存在 .env 里，加上 try/except 处理网络错误。
import requests
import os
import json
from dotenv import load_dotenv

load_dotenv()
API_KEY = os.getenv("DEEPSEEK_API_KEY")
URL = os.getenv("DEEPSEEK_URL")

def load_history():
    try:
        with open("history.json", "r", encoding="utf-8") as f:
            return json.load(f)
    except:
        return []

def save_history(history):
    with open("history.json", "w", encoding="utf-8") as f:
        json.dump(history, f, ensure_ascii=False, indent=2)

def chat(history, q):
    history.append({"role": "user", "content": q})
    try:
        res = requests.post(URL, headers={"Authorization": f"Bearer {API_KEY}",
                                          "Content-Type":"application/json"},
                            json ={"model": "deepseek-chat", "messages": history},
                            timeout = 30)
        res.raise_for_status()
        
    except requests.RequestException as e:
        print(f"Error: {e}")
        print("网络错误，请稍后再试。")
        history.pop()
        return None
    
    reply = res.json()["choices"][0]["message"]["content"]
    history.append({"role": "assistant", "content": reply})
    save_history(history)
    return reply

history = load_history()
print("✅ 已加载历史对话")

while True:
    q = input("你: ")
    if q == "quit":
        print("再见!")
        break
    reply = chat(history, q)
    if reply:
        print(f"AI:{reply}")