import os
import shutil
import requests
from datetime import datetime
from config import BACKUP_PATH, DATABASE_PATH, ADMIN_IDS, BOT_TOKEN

async def backup_database():
    try:
        if not os.path.exists(BACKUP_PATH):
            os.makedirs(BACKUP_PATH)

        current_time = datetime.now().strftime("%Y_%m_%d_%H%M%S")
        backup_filename = f"database_backup_{current_time}.sqlite"
        backup_path = os.path.join(BACKUP_PATH, backup_filename)

        shutil.copy2(DATABASE_PATH, backup_path)
        send_backup_to_telegram(backup_path)
        print(f"Database backed up successfully at {backup_path}")
    except Exception as e:
        print(f"Error during backup: {e}")

def send_backup_to_telegram(file_path):
    TELEGRAM_API_URL = f"https://api.telegram.org/bot{BOT_TOKEN}/sendDocument"
    try:
        with open(file_path, "rb") as file:
            for admin_id in ADMIN_IDS:
                try:
                    response = requests.post(
                        TELEGRAM_API_URL,
                        data={"chat_id": admin_id},
                        files={"document": file}
                    )
                    if response.status_code == 200:
                        print(f"Backup sent to admin {admin_id} successfully")
                    else:
                        print(f"Failed to send backup to admin {admin_id}: {response.text}")
                except Exception as e:
                    print(f"Error sending backup to admin {admin_id}: {e}")
                
                # Reset file pointer for next admin
                file.seek(0)
    except Exception as e:
        print(f"Error sending backup: {e}")