#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
定时备份 + 飞书云盘上传
自动执行备份并尝试上传到飞书
"""

import os
import sys
import json
from datetime import datetime
from pathlib import Path

# 项目路径
PROJECT_DIR = os.path.expanduser("~/openclaw-memory-vector")
sys.path.insert(0, PROJECT_DIR)

# 飞书配置
FEISHU_FOLDER_TOKEN = "GE2hfjECFlSSaedOFNccWhEknUf"  # 向量记忆系统文件夹


def upload_to_feishu(file_path: str):
    """上传文件到飞书云盘"""
    from feishu_drive_file import upload as feishu_upload
    
    file_name = os.path.basename(file_path)
    file_size = os.path.getsize(file_path)
    
    # 读取文件内容
    with open(file_path, 'rb') as f:
        file_content = f.read()
    
    import base64
    file_content_b64 = base64.b64encode(file_content).decode('utf-8')
    
    try:
        result = feishu_upload(
            file_path=file_path,
            parent_node=FEISHU_FOLDER_TOKEN
        )
        return result
    except Exception as e:
        print(f"⚠️ 自动上传暂不可用: {e}")
        return None


def run_backup():
    """执行备份"""
    print(f"\n{'='*60}")
    print(f"🧠 定时备份任务 | {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"{'='*60}")
    
    # 切换到项目目录
    os.chdir(PROJECT_DIR)
    
    # 设置环境变量
    os.environ["SILICONFLOW_API_KEY"] = "sk-fpjdtxbxrhtekshircjhegstloxaodriekotjdyzzktyegcl"
    
    # 导入模块
    from vector_memory import VectorMemorySystem
    from memory_backup import MemoryBackup
    
    # 执行备份
    api_key = os.getenv("SILICONFLOW_API_KEY")
    vm = VectorMemorySystem(api_key=api_key)
    backup = MemoryBackup()
    result = backup.backup_all(vm)
    
    print(f"\n✅ 本地备份完成!")
    print(f"   - JSON: {result['json']}")
    print(f"   - Markdown: {result['markdown']}")
    
    # 上传到飞书（尝试）
    print(f"\n📤 尝试上传到飞书云盘...")
    json_file = result['json']
    
    # 注意：飞书上传需要应用权限，这里只是记录
    print(f"   📋 备份文件: {json_file}")
    print(f"   💡 如需自动上传，请在飞书云盘手动上传或配置应用权限")
    
    return result


if __name__ == "__main__":
    run_backup()
