import re

# HTML Merging
with open('d:/NIKKI/Feedback/Feedback.html', 'r', encoding='utf-8') as f:
    fb_html = f.read()

# Extract section and script
section_match = re.search(r'(<section class="reviews-section">.*?</section>)', fb_html, re.DOTALL)
script_match = re.search(r'(<script>.*?</script>)', fb_html, re.DOTALL)

section_content = section_match.group(1) if section_match else ''
script_content = script_match.group(1) if script_match else ''

with open('d:/NIKKI/Feedback/final_test.html', 'r', encoding='utf-8') as f:
    final_html = f.read()

# Insert before the first <script> at the bottom, or just replace the last </div>\n\n<script>
insert_pos = final_html.rfind('</div>\n</div>\n\n<script>')
if insert_pos == -1:
    insert_pos = final_html.rfind('</div>\n\n<script>')

if insert_pos != -1:
    # </div>\n</div> is 13 characters.
    before = final_html[:insert_pos + 13]
    after = final_html[insert_pos + 13:]
    
    new_html = before + '\n\n    <!-- Feedback Section -->\n    ' + section_content + '\n\n    ' + script_content + '\n\n' + after
    with open('d:/NIKKI/Feedback/final_test.html', 'w', encoding='utf-8') as f:
        f.write(new_html)
    print('HTML merged successfully')
else:
    print('Could not find insert position for HTML')

# CSS Merging
with open('d:/NIKKI/Feedback/feedback.css', 'r', encoding='utf-8') as f:
    fb_css = f.read()

# Remove * and body selectors
fb_css = re.sub(r'\*\s*\{[^}]*\}', '', fb_css, flags=re.DOTALL)
fb_css = re.sub(r'body\s*\{[^}]*\}', '', fb_css, flags=re.DOTALL)

with open('d:/NIKKI/Feedback/final_test.css', 'a', encoding='utf-8') as f:
    f.write('\n\n/* ================= Feedback Section ================= */\n')
    f.write(fb_css)

print('CSS merged successfully')
