
import os
import sys
import json
from pathlib import Path

# Add project root to path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from app.core.utils.cloud_sync import GiteaSync
from app.config.settings import ConfigManager

def sync_all():
    config = ConfigManager()
    sync = GiteaSync.from_config(config)
    if not sync:
        print("Error: Gitea configuration missing in config.ini")
        sys.exit(1)

    # Sync files defined in dialog_utils.py (re-implementing the logic here)
    SYNC_FILES = [
        {"name": "条码映射", "remote": "barcode_mappings.json", "local": "config/barcode_mappings.json", "type": "json"},
        {"name": "供应商配置", "remote": "suppliers_config.json", "local": "config/suppliers_config.json", "type": "json"},
        {"name": "商品资料", "remote": "templates/商品资料.xlsx", "local": "templates/商品资料.xlsx", "type": "binary"},
        {"name": "采购单模板", "remote": "templates/银豹-采购单模板.xls", "local": "templates/银豹-采购单模板.xls", "type": "binary"},
        {"name": "商品记忆库 (DB)", "remote": "product_cache.db", "local": "data/product_cache.db", "type": "binary"},
    ]

    print(f"Starting sync to {sync.base_url}/{sync.owner}/{sync.repo}...")
    
    success_count = 0
    for entry in SYNC_FILES:
        local_path = entry["local"]
        remote_path = entry["remote"]
        name = entry["name"]
        
        if not os.path.exists(local_path):
            print(f"Skipping {name}: Local file not found at {local_path}")
            continue
            
        print(f"Pushing {name} ({local_path}) -> {remote_path}...")
        try:
            if entry["type"] == "json":
                with open(local_path, "r", encoding="utf-8") as f:
                    data = json.load(f)
                # Get current SHA to update
                sha = sync.file_exists(remote_path)
                result = sync.push_json(remote_path, data, f"Sync: {name}", sha=sha)
            else:
                result = sync.push_binary(remote_path, local_path, f"Sync: {name}")
            
            if result:
                print(f"Successfully synced {name}")
                success_count += 1
            else:
                print(f"Failed to sync {name}")
        except Exception as e:
            print(f"Error syncing {name}: {e}")

    print(f"\nSync finished. {success_count}/{len(SYNC_FILES)} files synced.")

if __name__ == "__main__":
    sync_all()
