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

url = "https://sarabeauty.ae/about-us/"
print(f"Fetching {url}...")
req = urllib.request.Request(url, 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')

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

main_content = soup.find(lambda tag: tag.name == 'div' and tag.get('data-elementor-type') == 'wp-page')
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>"

# Extract specific stylesheets for this page from the head
head_styles = ""
head = soup.find('head')
if head:
    for link in head.find_all('link', rel='stylesheet'):
        href = link.get('href', '')
        # If it's a post-specific stylesheet (e.g. post-205.css)
        if 'post-' in href and href.endswith('.css'):
            head_styles += str(link) + "\n"


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)
    
    # Add domain to relative asset URLs
    text = re.sub(r'(href|src|srcset|data-lazy-src)=["\']/(wp-content|wp-includes|wp-json)([^"\']*)["\']', r'\1="https://sarabeauty.ae/\2\3"', text)
    
    # Add domain to inline CSS url()
    text = re.sub(r'url\([\'"]?/(wp-content|wp-includes)([^)\'"]*)[\'"]?\)', r'url(https://sarabeauty.ae/\1\2)', text)

    # Escape @ inside JSON-LD
    text = text.replace('"@', '"@@')
    return text

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

with open('resources/views/about.blade.php', 'w', encoding='utf-8') as f:
    f.write(about_html)

print("Scraped about.blade.php successfully!")
