import json
import sys
import pymysql
from b2sdk.v1 import InMemoryAccountInfo, B2Api

# Function to get B2 credentials from the MySQL database
def get_b2_credentials(bucket_name):
    try:
        connection = pymysql.connect(
            host='127.0.0.1',
            user='uploadprocessor',
            password='UploadMyPh0to',
            database='timelapse'
        )
        with connection.cursor(pymysql.cursors.DictCursor) as cursor:
            query = """select bb.accId as account_id,bb.appKey as application_key,bb.appKeyId as application_key_id,bb.region as region,cs.cloudStorage,cs.cloudStorageFullsize from backBlazeKeys as bb left join cameraSettings as cs on bb.accId = cs.cloudStorageAccount where cs.cameraName=%s and bb.keyName='php-scripting-rw'"""
            cursor.execute(query, (bucket_name,))
            result = cursor.fetchone()
            return result
    except pymysql.MySQLError as e:
        print(f"Error while connecting to MySQL: {e}")
        return None
    finally:
        if connection:
            connection.close()

# Function to make the bucket public
def make_bucket_public(bucket_name, b2_api, account_id):
    try:
        bucket = b2_api.get_bucket_by_name(bucket_name)
        bucket_id = bucket.id_

        # Update the bucket type to 'allPublic'
        b2_api.session.update_bucket(
            account_id=account_id,
            bucket_id=bucket_id,
            bucket_type='allPublic'
        )
        print(f"Bucket '{bucket_name}' is now public.")
    except Exception as e:
        print(f"Error making bucket '{bucket_name}' public: {e}")
        sys.exit(1)

# Function to dynamically get the endpoint for a bucket
def get_bucket_endpoint(bucket_name, b2_api):
    try:
        # Retrieve the API URL
        api_url = b2_api.account_info.get_api_url()

        # Construct the bucket-specific endpoint
        bucket_endpoint = f"{api_url}/file/{bucket_name}"
        return bucket_endpoint
    except Exception as e:
        print(f"Error retrieving endpoint for bucket '{bucket_name}': {e}")
        sys.exit(1)

# Function to list files in the B2 bucket and export to JSON
def list_files(bucket_name):
    credentials = get_b2_credentials(bucket_name)
    if not credentials:
        print(f"No credentials found for bucket: {bucket_name}")
        sys.exit(1)

    application_key_id = credentials['application_key_id']
    application_key = credentials['application_key']
    account_id = credentials['account_id']

    # Connect to B2
    info = InMemoryAccountInfo()
    b2_api = B2Api(info)
    b2_api.authorize_account("production", application_key_id, application_key)

    # Ensure bucket is public
    make_bucket_public(bucket_name, b2_api, account_id)

    # Get bucket and file list
    try:
        bucket = b2_api.get_bucket_by_name(bucket_name)
        files = bucket.ls(recursive=True)

        # Get the bucket-specific endpoint
        endpoint = get_bucket_endpoint(bucket_name, b2_api)
    except Exception as e:
        print(f"Error listing files for bucket '{bucket_name}': {e}")
        sys.exit(1)

    file_list = []
    for file_info, _ in files:
        # Generate the friendly and cdn URLs
        friendly_url = f"{endpoint}/{file_info.file_name}"  # Use the endpoint URL for friendly_url
        cdn_url = f"https://images.livetimelapse.com.au/{bucket_name}/{file_info.file_name}"

        # Create file entry
        file_entry = {
            'bucket_name': bucket_name,
            'path': file_info.file_name,
            'filename': file_info.file_name.split('/')[-1],
            'filesize': file_info.size,
            'download_url': b2_api.get_download_url_for_fileid(file_info.id_),
            'friendly': friendly_url,  # Updated to use the endpoint URL
            'cdn': cdn_url
        }
        file_list.append(file_entry)

    # Export to JSON file
    output_file = f"data/{bucket_name}_file_list.json"
    try:
        with open(output_file, 'w') as json_file:
            json.dump(file_list, json_file, indent=4)
        print(f"File list exported to {output_file}")
    except Exception as e:
        print(f"Error exporting file list to JSON: {e}")
        sys.exit(1)

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print("Usage: python3 b2_list_files.py <bucket_name>")
        sys.exit(1)

    bucket_name = sys.argv[1].replace('_', '-')
    list_files(bucket_name)
