import os

HISTORY_FILE = "calc_history.txt"
DEFAULT_SHOW = 10

# 运算函数
def jia(a,b): return a+b
def jian(a,b): return a-b
def cheng(a,b): return a*b
def chu(a,b):
    if b==0: raise ZeroDivisionError("除数不能为0")
    return a/b
def mo(a,b):
    if b==0: raise ZeroDivisionError("取模不能为0")
    return a%b
def mi(a,b): return a**b

# 历史记录
def save(expr, res):
    try:
        with open(HISTORY_FILE,"a",encoding="utf-8") as f:
            f.write(f"{expr} = {res}\n")
    except:
        print("保存历史失败")

def load(count=DEFAULT_SHOW):
    if not os.path.exists(HISTORY_FILE): return []
    try:
        with open(HISTORY_FILE,"r",encoding="utf-8") as f:
            return f.readlines()[-count:]
    except:
        return []

def clear():
    try:
        open(HISTORY_FILE,"w").close()
        print("✅ 已清空历史")
    except:
        print("清空失败")

# 安全输入数字
def input_num(prompt="请输入数字："):
    while True:
        try:
            return float(input(prompt))
        except ValueError:
            print("❌ 请输入数字")

# 主菜单
def main():
    last = None
    while True:
        print("\n===== 计算器菜单 =====")
        print("1 开始运算")
        print("2 查看历史")
        print("3 清空历史")
        print("0 退出")
        c = input("请选择：").strip()

        if c=="0":
            print("\n感谢使用，再见！")
            break

        elif c=="1":
            print("\n1加 2减 3乘 4除 5取模 6幂")
            op = input("运算类型：").strip()
            op_map = {
                "1":("加法",jia),
                "2":("减法",jian),
                "3":("乘法",cheng),
                "4":("除法",chu),
                "5":("取模",mo),
                "6":("幂运算",mi)
            }
            if op not in op_map:
                print("无效选项")
                continue
            name,func = op_map[op]

            # 连续运算
            if last is not None:
                use = input(f"用上次结果 {last} 做第一个数？(y/n)：")
                if use.lower()=="y":
                    a = last
                else:
                    a = input_num()
            else:
                a = input_num()
            b = input_num()

            try:
                res = func(a,b)
                expr = f"{a}{name}{b}"
                print(f"✅ {expr} = {res}")
                save(expr,res)
                last = res
            except ZeroDivisionError as e:
                print(f"错误：{e}")
            except:
                print("运算出错")

        elif c=="2":
            print("\n--- 最近记录 ---")
            lines = load()
            if not lines:
                print("暂无记录")
            else:
                for line in lines:
                    print(line.strip())

        elif c=="3":
            if input("确定清空？(y/n)：").lower()=="y":
                clear()

        else:
            print("请输入0-3")

if __name__ == "__main__":
    main()
