import os
import datetime
import re
import zipfile

def create_backup():
    """
    建立系統完整備份 (Zip 壓縮檔)
    檔名格式: momo_pro_system_backup_YYYYMMDD_HHMMSS_V{version}.zip
    """
    # 1. 基礎路徑設定
    base_dir = os.path.dirname(os.path.abspath(__file__))
    backup_folder = os.path.join(base_dir, 'backups')
    
    if not os.path.exists(backup_folder):
        os.makedirs(backup_folder)
        print(f"📂 已建立備份目錄: {backup_folder}")

    # 2. 嘗試從 app.py 讀取版本號
    version = "Unknown"
    app_py_path = os.path.join(base_dir, 'app.py')
    try:
        if os.path.exists(app_py_path):
            with open(app_py_path, 'r', encoding='utf-8') as f:
                content = f.read()
                # 尋找 SYSTEM_VERSION = "V9.0"
                match = re.search(r'SYSTEM_VERSION\s*=\s*["\']([^"\']+)["\']', content)
                if match:
                    version = match.group(1)
    except Exception as e:
        print(f"⚠️ 無法讀取版本號: {e}")

    # 3. 產生備份檔名
    timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
    base_name = f"momo_pro_system_backup_{timestamp}_{version}.zip"
    output_path = os.path.join(backup_folder, base_name)

    print(f"📦 正在打包專案目錄: {base_dir}")
    print(f"🎯 目標檔案: {output_path}")

    # 4. 執行壓縮
    try:
        with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
            for root, dirs, files in os.walk(base_dir):
                # 排除不需要備份的目錄
                for ignore in ['backups', '__pycache__', '.git', '.idea', '.vscode', 'bin', 'bin 2']:
                    if ignore in dirs:
                        dirs.remove(ignore)
                
                for file in files:
                    if file == '.DS_Store' or file.endswith('.pyc'): continue
                    file_path = os.path.join(root, file)
                    arcname = os.path.relpath(file_path, base_dir)
                    zipf.write(file_path, arcname)
        print(f"✅ 備份完成！")
    except Exception as e:
        print(f"❌ 備份失敗: {e}")

if __name__ == "__main__":
    create_backup()