import urllib.request
from bs4 import BeautifulSoup
import re
import gzip
import os

pages = [
    "blogs",
]

os.makedirs('resources/views/pages', exist_ok=True)

def make_spa(text):
    text = re.sub(r'<a([^>]+)href=["\']https://sarabeauty\.ae/([^"\']*)["\']', r'<a\1href="/\2" wire:navigate', text)
    text = re.sub(r'<a([^>]+)href=["\']https://sarabeauty\.ae["\']', r'<a\1href="/" wire:navigate', text)
    text = re.sub(r'(href|src|srcset|data-lazy-src)=["\']/(wp-content|wp-includes|wp-json)([^"\']*)["\']', r'\1="https://sarabeauty.ae/\2\3"', text)
    text = re.sub(r'url\([\'"]?/(wp-content|wp-includes)([^)\'"]*)[\'"]?\)', r'url(https://sarabeauty.ae/\1\2)', text)
    text = text.replace('"@', '"@@')
    return text

for slug in pages:
    url = f"https://sarabeauty.ae/{slug}/"
    print(f"Fetching {url}...")
    try:
        req = urllib.request.Request(url + "?nocache=1", headers={'User-Agent': 'Mozilla/5.0', 'Accept-Encoding': 'identity'})
        with urllib.request.urlopen(req) as response:
            data = response.read()
            if response.info().get('Content-Encoding') == 'gzip':
                data = gzip.decompress(data)
            html = data.decode('utf-8')
    except Exception as e:
        print(f"Error fetching {slug}: {e}")
        continue

    soup = BeautifulSoup(html, 'html.parser')

    main_content = soup.find('div', {'data-elementor-type': 'wp-page'})
    if not main_content:
        main_content = soup.find('div', {'data-elementor-type': 'single-post'})
    if not main_content:
        main_content = soup.find('div', {'data-elementor-type': 'archive'})
    if not main_content:
        main_content = soup.find('main')

    if main_content:
        main_html = str(main_content)
    else:
        main_html = "<h1>Could not find main content</h1>"

    head_styles = ""
    head = soup.find('head')
    if head:
        for link in head.find_all('link', rel='stylesheet'):
            href = link.get('href', '')
            if 'post-' in href or 'dynamic-content-for-elementor' in href or 'elementskit' in href or 'fluentform' in href:
                head_styles += str(link) + "\n"

    head_styles = re.sub(r'(\.css)\?[^"\']+', r'\1', head_styles)

    main_html = re.sub(r'data-dce-background-image-url=["\']([^"\']+)["\']', r'style="background-image: url(\1); background-size: cover; background-position: center; background-repeat: no-repeat;"', main_html)

    faq_js = """
    <style>
    .dce-acf-repeater .item > div:not(.heading) {
        display: none;
    }
    .dce-acf-repeater .item.active > div:not(.heading) {
        display: block;
        padding-top: 15px;
    }
    .dce-acf-repeater .item .heading {
        cursor: pointer;
    }
    .dce-acf-repeater .item .icon-active {
        display: none !important;
    }
    .dce-acf-repeater .item.active .icon-active {
        display: inline-block !important;
    }
    .dce-acf-repeater .item.active .icon:not(.icon-active) {
        display: none !important;
    }
    </style>
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        document.querySelectorAll('.dce-acf-repeater .item .heading').forEach(function(heading) {
            heading.addEventListener('click', function() {
                var item = this.parentElement;
                item.classList.toggle('active');
            });
        });
    });
    </script>
    """

    final_html = "<x-layouts.app>\n" + make_spa(head_styles) + "\n" + make_spa(main_html) + faq_js + "\n</x-layouts.app>"

    with open(f'resources/views/pages/{slug}.blade.php', 'w', encoding='utf-8') as f:
        f.write(final_html)

print("Scraped all pages successfully!")
