import os
import mysql.connector

def create_html_files():
    conn = None  # Initialize the connection variable
    try:
        # Read environment variables
        db_config = {
            'user': os.getenv('DB_USER'),
            'password': os.getenv('DB_PASSWORD'),
            'host': os.getenv('DB_HOST'),
            'database': os.getenv('DB_NAME'),
            'port': int(os.getenv('DB_PORT', 3306))  # Default MySQL port is 3306
        }
        
        # Attempt to connect to the MySQL database
        conn = mysql.connector.connect(**db_config)
        cursor = conn.cursor()
        
        # Specify the base directory where campaign directories will be created
        base_directory = "/var/www/html/campaigns"
        
        # Ensure the base directory exists
        if not os.path.exists(base_directory):
            os.makedirs(base_directory)

        # Query to fetch documents with campaign_code
        query = "SELECT uuid, document, campaign_code FROM tbl_tracker"
        cursor.execute(query)

        for uuid, document, campaign_code in cursor:
            # Skip if campaign_code is None
            if campaign_code is None:
                continue
                
            # Create directory for this campaign if it doesn't exist
            campaign_directory = os.path.join(base_directory, campaign_code)
            if not os.path.exists(campaign_directory):
                os.makedirs(campaign_directory)
            
            # Assuming document is stored in a binary format that needs decoding
            try:
                html_content = document.decode('utf-8')
                file_name = f"{uuid}.html"
                file_path = os.path.join(campaign_directory, file_name)
                with open(file_path, 'w') as file:
                    file.write(f"<!-- Document UUID: {uuid} -->\n{html_content}")
                print(f"Created file for UUID: {uuid} in campaign: {campaign_code}")
            except (AttributeError, UnicodeDecodeError) as e:
                print(f"Error processing document for UUID {uuid}: {e}")

        # Close the cursor after operations
        cursor.close()
    except mysql.connector.Error as err:
        print("Error connecting to MySQL:", err)
    finally:
        # Ensure the connection is closed even if an error occurred
        if conn is not None and conn.is_connected():
            conn.close()
            print("Database connection closed.")

if __name__ == "__main__":
    create_html_files()