from bs4 import BeautifulSoup
import json

def generate_form_names(html_content):
    """
    Generates unique form names for text and image elements in an HTML page, modifies the HTML, and creates a corresponding JSON file.

    1. Parses the HTML to locate text (h1, h2, h3, p) and image (img) elements.
    
    2. For each element found:
        - Generates a unique form name using the format `{page-class-name}_{parent-class-name}_{element-type}_{index}`.
        - Assigns the form name as an `id` attribute and replaces text content or image `src` with Django's template syntax.
    
    3. Builds a JSON file containing form names, element types, and metadata like `sub_type` and `tags`.
    
    4. Returns the modified HTML with form names and a JSON structure for further use.
    
    This automates form name generation and content replacement, simplifying integration with CMS app.
    """
    
    # Parse the HTML content
    soup = BeautifulSoup(html_content, 'html.parser')

    json_output = {
        "About": []
    }

    text_counter = 0 #FIX TEXT COUNTER TO BE FOR EACH ELEMNT
    img_counter = 0

    # Find all divs with the 'page' class
    for page_div in soup.find_all('div', class_='page'):
        page_class = page_div.get('class')[0]  # Get the first class as the page name

        # For each text element (h1, h2, h3, p)
        for el in page_div.find_all(['h1', 'h2', 'h3', 'p']):
            parent_class = el.find_parent().get('class')[0]  # Get the parent's class name
            tag_name = el.name.lower()  # Element type (e.g., h1, h3, etc.)
            unique_form_name = f"{page_class}_{parent_class}_{tag_name}_{text_counter}"
            text_counter += 1

            # Set the ID in the HTML
            el['id'] = unique_form_name

            # Update the content with Django template tag
            el.string = f"{{{{content.{unique_form_name}}}}}"

            # Add to the JSON output
            json_output["About"].append({
                "title": "Lorem Ipsum",
                "type": "text",
                "max_length": 255,
                "form_name": unique_form_name,
                "sub_type": "regular_field",
                "tags": ""
            })

        # For each image element
        for img in page_div.find_all('img'):
            parent_class = img.find_parent().get('class')[0]  # Get the parent's class name
            tag_name = img.name.lower()  # Should always be 'img'
            unique_form_name = f"{page_class}_{parent_class}_{tag_name}_{img_counter}"
            img_counter += 1

            # Set the ID in the HTML
            img['id'] = unique_form_name

            # Update the 'src' with Django template tag
            img['src'] = f"{{% static 'img/' %}}{{{{content.{unique_form_name}}}}}"

            # Add to the JSON output
            json_output["About"].append({
                "title": "Lorem Ipsum",
                "type": "image",
                "form_name": unique_form_name,
                "sub_type": "drop_down",
                "tags": "img"
            })

    # Convert modified soup object back to a string
    modified_html = str(soup)

    # Convert json_output to a JSON string
    json_string = json.dumps(json_output, indent=4)

    # Return the modified HTML and JSON
    return modified_html, json_string


# Example HTML input
html_content = """
<head>

    {% load static %}  <!-- Load static files like CSS, JS, images -->
    {% load widget_tweaks %}  <!-- Load widget tweaks for customizing form widgets -->

    <title>CMS - Demo</title>

    <link rel="stylesheet" href="{% static 'css/demo.css' %}">

    <!-- Libraries -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">  <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">  <!-- Bootstrap Icons -->

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>  <!-- jQuery (slim version) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>  <!-- Popper.js -->
</head>

<body>
    <div class="pages_container">

        <div class="landing page">
    
            <div class="title">
                <h1>Company Profile Template Demo</h1>
            </div>
    
            <div class="text_container">
                <!--Demo Text being called-->
    
                <h3>Hi thereeeee</h3>
                <img src="{% static 'img/' %}/formal.jpg" alt=""> <!--Image Calling-->
    
            </div>
        </div>
        
        <div class="about page">
    
            <div class="title">
                <h1>Company Profile Template Demo</h1>
            </div>
    
            <div class="text_container">
                <!--Demo Text being called-->
    
                <h3>Hi thereeeee</h3>
                <img src="{% static 'img/' %}/formal.jpg" alt=""> <!--Image Calling-->
    
            </div>
        </div>
        
    </div>

    <!-- END -->
    
    <!--DOM Scripts-->
    <script src="{% static 'css/general/header_ext.js' %}"></script>

    <!------------------------------------------------------------------------>

    <!-- Libraries Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
        crossorigin="anonymous"></script>  <!-- Bootstrap JavaScript -->
    <script src="https://code.jquery.com/jquery-3.6.4.min.js" integrity="sha384-oPz3JYfPLTYjvnQoZ79Zl5Fs3S8Wu16L+91NE3shOjeW4zh26RY7fH0U0fBblvvV" crossorigin="anonymous"></script>  <!-- jQuery -->
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-oBqDVmMz4fnFO9dT3GaaSHH8Zx02HAY8B7W+Xq2j8WEWo6K13nW+YwY/7ZzShkp" crossorigin="anonymous"></script>  <!-- Popper.js -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/5.3.0/js/bootstrap.min.js" integrity="sha384-DbfPgfTvsY6fMhsTSTx3C2wDFzC53GRM0pQwlN5eG9e6RjzsmDQ5DSr1vH8Q07lF" crossorigin="anonymous"></script>  <!-- Additional Bootstrap JavaScript -->
    <script src="https://kit.fontawesome.com/a5ffb044c8.js" crossorigin="anonymous"></script>  <!-- Font Awesome icons -->
    
</body>
"""

# Call the function to generate form names and modify HTML
modified_html, json_output = generate_form_names(html_content)

# Save the modified HTML to a file
with open('modified_about.html', 'w') as html_file:
    html_file.write(modified_html)

# Save the JSON output to a file
with open('about_content_index.json', 'w') as json_file:
    json_file.write(json_output)

# Output to verify
print("Modified HTML:")
print(modified_html)
print("\nGenerated JSON:")
print(json_output)
