import os
import socket
import shutil
import subprocess
import json
import random

# 🔹 自动安装 requests(如果未安装)
try:
    import requests
except ImportError:
    print("CGG-EUSO: 'requests' 模块未找到,正在自动安装...")
    os.system("pip install requests")
    try:
        import requests  # 再次尝试导入
    except ImportError:
        print("CGG-EUSO: 自动安装失败,请手动安装 'requests' 模块!")
        exit()

# 文件路径
USER_PROFILE_FILE = "user_profile.json"
CHAT_HISTORY_FILE = "chat_history.json"
KNOWLEDGE_FILE = "knowledge.json"

# 读取文件数据
def load_json_file(filename, default_data):
    if os.path.exists(filename):
        try:
            with open(filename, 'r', encoding='utf-8') as f:
                return json.load(f)
        except (json.JSONDecodeError, IOError):
            print(f"CGG-EUSO: 读取 {filename} 失败,正在创建新文件。")
    return default_data

# 保存文件数据
def save_json_file(filename, data):
    try:
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=4, ensure_ascii=False)
    except IOError:
        print(f"CGG-EUSO: 无法保存数据到 {filename}。")

# 载入数据
user_profile = load_json_file(USER_PROFILE_FILE, {"name": None, "preferred_style": "neutral"})
chat_history = load_json_file(CHAT_HISTORY_FILE, [])
knowledge_base = load_json_file(KNOWLEDGE_FILE, {})

# 互联网连接检查
def check_internet():
    try:
        socket.setdefaulttimeout(3)
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect(("8.8.8.8", 53))
        return True
    except Exception:
        return False

# 智能搜索:获取多个来源并总结
def search_online(query):
    url = f"https://api.duckduckgo.com/?q={query}&format=json"
    try:
        response = requests.get(url)
        data = response.json()
        summary = data.get("AbstractText", "").strip()
        return summary if summary else None
    except Exception:
        return None

# 处理聊天记录
def log_chat(user_input, response):
    chat_history.append({"user": user_input, "CGG-EUSO": response})
    save_json_file(CHAT_HISTORY_FILE, chat_history)

# 设定个性化风格
def format_response(response):
    styles = {
        "neutral": response,
        "formal": f"尊敬的用户,{response}",
        "casual": f"嘿!{response}",
        "humorous": f"😂 你知道吗?{response}"
    }
    return styles.get(user_profile["preferred_style"], response)

# 聊天机器人主逻辑
def chatbot():
    global knowledge_base

    if not user_profile["name"]:
        user_profile["name"] = input("CGG-EUSO: 你好!请问你的名字是什么?(What's your name?) ").strip()
        save_json_file(USER_PROFILE_FILE, user_profile)

    print(f"CGG-EUSO: 欢迎回来,{user_profile['name']}!输入 'exit' 退出聊天。")

    while True:
        user_input = input("你 (You): ").strip()
        if user_input.lower() == "exit":
            break

        # 检查知识库
        if user_input in knowledge_base:
            response = format_response(knowledge_base[user_input])
            print(f"CGG-EUSO: {response}")
            log_chat(user_input, response)
            continue

        # 在线搜索
        if check_internet():
            print("CGG-EUSO: 我在线上,正在搜索答案...")
            online_answer = search_online(user_input)
            if online_answer:
                response = format_response(online_answer)
                print(f"CGG-EUSO (来自网络): {response}")
                knowledge_base[user_input] = online_answer
                save_json_file(KNOWLEDGE_FILE, knowledge_base)
                log_chat(user_input, response)
                continue

        # 让用户提供答案
        print("CGG-EUSO: 我不知道这个问题的答案,你能告诉我该如何回答吗?")
        user_response = input("请输入正确答案: ").strip()

        knowledge_base[user_input] = user_response
        save_json_file(KNOWLEDGE_FILE, knowledge_base)
        response = format_response(user_response)
        print(f"CGG-EUSO: 记住了!{response}")
        log_chat(user_input, response)

# 代码检查功能
def code_check():
    try:
        filename = __file__
    except NameError:
        print("错误:无法显示代码,__file__ 未定义。")
        return
    with open(filename, 'r', encoding='utf-8') as f:
        print("\n----- CGG-EUSO 当前代码 (Current Code) -----\n")
        print(f.read())
        print("----- 代码结束 (End of Code) -----\n")

# 允许用户自定义 AI 的风格
def customize_personality():
    print("\n个性化设置:")
    print("1. 正常 (Neutral)")
    print("2. 正式 (Formal)")
    print("3. 休闲 (Casual)")
    print("4. 幽默 (Humorous)")
    
    choice = input("选择你的风格 (Select your style): ").strip()
    styles = {"1": "neutral", "2": "formal", "3": "casual", "4": "humorous"}

    if choice in styles:
        user_profile["preferred_style"] = styles[choice]
        save_json_file(USER_PROFILE_FILE, user_profile)
        print(f"CGG-EUSO: 你的风格已更改为 {styles[choice]}!")
    else:
        print("无效选择,保持当前风格。")

# 主菜单
def main():
    while True:
        print("\n请选择一个选项:")
        print("1. 聊天 (Chat)")
        print("2. 查看代码 (Code Check)")
        print("3. 自定义 AI 风格 (Customize AI Personality)")
        print("4. 退出 (Exit)")
        choice = input("你的选择: ").strip()

        if choice == "1":
            chatbot()
        elif choice == "2":
            code_check()
        elif choice == "3":
            customize_personality()
        elif choice == "4":
            print("退出 CGG-EUSO。再见!")
            break
        else:
            print("无效选项,请重试。")

if __name__ == "__main__":
    main()