import json
import pymysql
from b2sdk.v2 import InMemoryAccountInfo, B2Api

# MySQL Database Configurations
db_config = {
    "host": "127.0.0.1",
    "user": "uploadprocessor",
    "password": "UploadMyPh0to",
    "database": "timelapse"
}

# Path to save the JSON output
output_file = "b2_accounts_and_buckets.json"

def fetch_b2_accounts():
    """Fetch B2 accounts from the MySQL database."""
    connection = pymysql.connect(**db_config)
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT appKeyId as account_id, appKey as application_key FROM backBlazeKeys WHERE keyName='PHP-Scripting-RO'")
            accounts = cursor.fetchall()
            return [{"account_id": row[0], "application_key": row[1]} for row in accounts]
    finally:
        connection.close()

def get_bucket_details(account_id, application_key):
    """Fetch all static information for each bucket in a specific Backblaze B2 account."""
    try:
        account_info = InMemoryAccountInfo()
        b2_api = B2Api(account_info)
        b2_api.authorize_account("production", account_id, application_key)

        # List all buckets and their static details
        bucket_details = []
        for bucket in b2_api.list_buckets():
            encryption_mode = (
                bucket.default_server_side_encryption.mode.name
                if bucket.default_server_side_encryption
                else "Disabled"
            )
            bucket_details.append({
                "bucket_id": bucket.id_,
                "bucket_name": bucket.name,
                "bucket_type": bucket.type_,
                "bucket_info": bucket.bucket_info,
                "lifecycle_rules": bucket.lifecycle_rules,
                "revision": bucket.revision,
                "encryption_mode": encryption_mode,
                "s3_api_url": account_info.get_s3_api_url(),
                "b2_api_url": account_info.get_api_url(),
            })
        return bucket_details
    except Exception as e:
        print(f"Error fetching bucket details for account {account_id}: {e}")
        return []

def main():
    # Fetch accounts from the database
    accounts = fetch_b2_accounts()

    all_accounts_info = []

    # Process each account to retrieve bucket details
    for account in accounts:
        account_id = account["account_id"]
        application_key = account["application_key"]
        print(f"Fetching buckets for account ID: {account_id}")

        bucket_details = get_bucket_details(account_id, application_key)
        account_info = {
            "account_id": account_id,
            "buckets": bucket_details
        }
        all_accounts_info.append(account_info)

        # Display bucket details in the console
        for bucket in bucket_details:
            print(f"Bucket Name: {bucket['bucket_name']}")
            print(f"Bucket ID: {bucket['bucket_id']}")
            print(f"Bucket Type: {bucket['bucket_type']}")
            print(f"Bucket Info: {bucket['bucket_info']}")
            print(f"Lifecycle Rules: {bucket['lifecycle_rules']}")
            print(f"Revision: {bucket['revision']}")
            print(f"Encryption Mode: {bucket['encryption_mode']}")
            print(f"S3 API URL: {bucket['s3_api_url']}")
            print(f"B2 API URL: {bucket['b2_api_url']}")
            print("-" * 40)

    # Save the account and bucket details to a JSON file
    with open(output_file, "w") as f:
        json.dump(all_accounts_info, f, indent=4)
    print(f"Account and bucket information saved to {output_file}")

if __name__ == "__main__":
    main()
