# ==============================================
# 🌈 宇宙终极至尊完美版 · 智能通讯录管理系统
# ✔ 彩色界面 ✔ 全功能 ✔ 永不崩溃 ✔ 导入导出Excel ✔ 分组统计
# ✔ 去重 ✔ 异常捕获 ✔ 启动动画 ✔ 作者信息 ✔ 可打包EXE
# 作者：刘世强  | 版本：V10.0 终极完美版
# ==============================================
import json
import os
import time
import pandas as pd

# ===================== ANSI 颜色（Windows/Linux/Mac 全支持） =====================
RED = "\033[91m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
MAGENTA = "\033[95m"
CYAN = "\033[96m"
WHITE = "\033[97m"
BOLD = "\033[1m"
RESET = "\033[0m"

# ===================== 配置文件 =====================
CONTACTS_FILE = "contacts.json"
EXCEL_FILE = "contacts.xlsx"
AUTHOR = "刘世强"
VERSION = "V10.0 终极完美版"

# ===================== 工具函数 =====================
def load_contacts():
    if not os.path.exists(CONTACTS_FILE):
        return []
    try:
        with open(CONTACTS_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except:
        return []

def save_contacts(contacts):
    with open(CONTACTS_FILE, "w", encoding="utf-8") as f:
        json.dump(contacts, f, ensure_ascii=False, indent=4)

# ===================== 1. 添加联系人 =====================
def add_contact(name, phone, birthday="", email="", address="", group="默认", note=""):
    contacts = load_contacts()
    for c in contacts:
        if c["phone"] == phone:
            print(f"{RED}❌ 手机号已存在！{RESET}")
            return
    contacts.append({
        "name": name, "phone": phone, "birthday": birthday,
        "email": email, "address": address, "group": group, "note": note
    })
    save_contacts(contacts)
    print(f"{GREEN}✅ 添加成功：{name}{RESET}")

# ===================== 2. 搜索 =====================
def search(keyword):
    contacts = load_contacts()
    result = [c for c in contacts if any(keyword in str(v) for v in c.values())]
    if not result:
        print(f"{YELLOW}❌ 无匹配结果{RESET}")
        return
    print(f"\n{BOLD}{CYAN}📌 搜索结果：{RESET}")
    for i, c in enumerate(result, 1):
        print(f"{i:2d}. {BLUE}[{c['group']}]{RESET} {GREEN}{c['name']}{RESET} | {c['phone']} | {c['birthday']}")
        print(f"     {CYAN}邮箱：{RESET}{c['email']}  {CYAN}地址：{RESET}{c['address']}")
        print(f"     {YELLOW}备注：{RESET}{c['note']}\n")

# ===================== 3. 修改 =====================
def update(name):
    contacts = load_contacts()
    for c in contacts:
        if c["name"] == name:
            print(f"\n{CYAN}✏️ 修改信息（回车不改变）{RESET}")
            c["phone"] = input(f"{GREEN}电话 [{c['phone']}]: {RESET}") or c["phone"]
            c["birthday"] = input(f"{GREEN}生日 [{c['birthday']}]: {RESET}") or c["birthday"]
            c["email"] = input(f"{GREEN}邮箱 [{c['email']}]: {RESET}") or c["email"]
            c["address"] = input(f"{GREEN}地址 [{c['address']}]: {RESET}") or c["address"]
            c["group"] = input(f"{GREEN}分组 [{c['group']}]: {RESET}") or c["group"]
            c["note"] = input(f"{GREEN}备注 [{c['note']}]: {RESET}") or c["note"]
            save_contacts(contacts)
            print(f"{GREEN}✅ 修改成功！{RESET}")
            return
    print(f"{RED}❌ 未找到联系人{RESET}")

# ===================== 4. 删除 =====================
def delete(key):
    contacts = load_contacts()
    new_contacts = [c for c in contacts if c["name"] != key and c["phone"] != key]
    if len(new_contacts) < len(contacts):
        save_contacts(new_contacts)
        print(f"{GREEN}✅ 删除成功{RESET}")
    else:
        print(f"{RED}❌ 无匹配{RESET}")

# ===================== 5. 显示全部 =====================
def show_all():
    contacts = load_contacts()
    if not contacts:
        print(f"{YELLOW}📭 通讯录为空{RESET}")
        return
    print(f"\n{BOLD}{CYAN}📋 全部联系人（共{len(contacts)}人）：{RESET}")
    for i, c in enumerate(contacts, 1):
        print(f"{i:2d}. {BLUE}[{c['group']}]{RESET} {GREEN}{c['name']}{RESET} | {c['phone']} | {c['birthday']}")

# ===================== 6. 排序 =====================
def sort_by_name():
    contacts = load_contacts()
    contacts.sort(key=lambda x: x["name"])
    save_contacts(contacts)
    print(f"{GREEN}✅ 已按姓名排序{RESET}")

# ===================== 7. 分组筛选 =====================
def group_filter(g):
    lst = [c for c in load_contacts() if c["group"] == g]
    if not lst:
        print(f"{YELLOW}❌ 分组无数据{RESET}")
        return
    print(f"\n{BLUE}📂 分组 {g}：{RESET}")
    for i, c in enumerate(lst, 1):
        print(f"{i}. {c['name']} {c['phone']}")

# ===================== 8. 分组统计 =====================
def group_stat():
    contacts = load_contacts()
    stat = {}
    for c in contacts:
        g = c["group"]
        stat[g] = stat.get(g, 0) + 1
    print(f"\n{BOLD}{CYAN}📊 分组统计{RESET}")
    for g, n in stat.items():
        print(f"  {BLUE}{g}{RESET}: {GREEN}{n}人{RESET}")

# ===================== 9. 清空 =====================
def clear_all():
    if input(f"{RED}⚠️ 真清空？y/n: {RESET}").lower() == "y":
        save_contacts([])
        print(f"{RED}🗑️ 已清空{RESET}")

# ===================== 10. 导出Excel =====================
def export_excel():
    lst = load_contacts()
    if not lst:
        print(f"{YELLOW}❌ 无数据{RESET}")
        return
    pd.DataFrame(lst).to_excel(EXCEL_FILE, index=False)
    print(f"{GREEN}✅ 已导出 {EXCEL_FILE}{RESET}")

# ===================== 11. 导入Excel（自动去重） =====================
def import_excel():
    if not os.path.exists(EXCEL_FILE):
        print(f"{RED}❌ 文件不存在{RESET}")
        return
    df = pd.read_excel(EXCEL_FILE).fillna("")
    imported = df.to_dict("records")
    existing = load_contacts()
    phones = {c["phone"] for c in existing}
    new_contacts = [c for c in imported if c["phone"] not in phones]
    existing += new_contacts
    save_contacts(existing)
    print(f"{GREEN}✅ 导入成功，新增{len(new_contacts)}人{RESET}")

# ===================== 🌟 启动动画（超帅） =====================
def welcome():
    os.system("cls" if os.name == "nt" else "clear")
    print(f"{BOLD}{CYAN}")
    print("="*65)
    print("       📞  智 能 通 讯 录 管 理 系 统  ")
    print(f"            作者：{AUTHOR}  | 版本：{VERSION}")
    print("="*65)
    print(f"{RESET}")
    for i in range(3):
        print(f"{GREEN}正在加载系统{'.'*i}{RESET}", end="\r")
        time.sleep(0.3)
    print(f"{GREEN}✅ 系统加载完成！{RESET}")
    time.sleep(0.5)
    os.system("cls" if os.name == "nt" else "clear")

# ===================== 🎨 主菜单 =====================
def main():
    welcome()
    while True:
        print(f"{BOLD}{BLUE}┌─────────────────────────────────────┐{RESET}")
        print(f"{BLUE}│{RESET} 1.添加  2.搜索  3.修改  4.删除  5.全部  {BLUE}│{RESET}")
        print(f"{BLUE}│{RESET} 6.排序  7.分组  8.统计  9.清空 10.导出  {BLUE}│{RESET}")
        print(f"{BLUE}│{RESET} 11.导入         12.退出           {BLUE}│{RESET}")
        print(f"{BOLD}{BLUE}└─────────────────────────────────────┘{RESET}")

        choice = input(f"\n{BOLD}{WHITE}请选择功能：{RESET}").strip()
        try:
            if   choice == "1":
                name = input("姓名：")
                phone = input("电话：")
                if not name or not phone:
                    print(f"{RED}❌ 姓名电话不能为空{RESET}")
                    continue
                add_contact(name, phone, input("生日："), input("邮箱："), input("地址："), input("分组：") or "默认", input("备注："))
            elif choice == "2": search(input("关键词："))
            elif choice == "3": update(input("姓名："))
            elif choice == "4": delete(input("姓名/电话："))
            elif choice == "5": show_all()
            elif choice == "6": sort_by_name()
            elif choice == "7": group_filter(input("分组名："))
            elif choice == "8": group_stat()
            elif choice == "9": clear_all()
            elif choice == "10": export_excel()
            elif choice == "11": import_excel()
            elif choice == "12":
                if input(f"{YELLOW}确定退出？y/n: {RESET}").lower()=="y":
                    print(f"\n{GREEN}👋 感谢使用，祝您生活愉快！{RESET}")
                    break
            else:
                print(f"{RED}❌ 无效输入{RESET}")
        except Exception as e:
            print(f"{RED}⚠️ 异常：{str(e)}{RESET}")

if __name__ == "__main__":
    main()