import re
from bs4 import BeautifulSoup

with open('public/scraped.html', 'r', encoding='utf-8') as f:
    html = f.read()

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)
    # Replace the main_content in the soup with a placeholder
    slot_tag = soup.new_string("{{ $slot }}")
    main_content.replace_with(slot_tag)
else:
    main_html = "<h1>Could not find main content</h1>"

# Inject Livewire
head = soup.find('head')
if head:
    head.append(soup.new_string("\n    @livewireStyles\n"))

body = soup.find('body')
if body:
    body.append(soup.new_string("\n    @livewireScripts\n"))

# Render app.blade.php
app_html = str(soup)

# Add wire:navigate to local links
def make_spa(text):
    # Fix links in <a> tags
    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)

    # Fix the issue where my previous global replace was stripping the domain
    text = text.replace('href=""', 'href="/"')
    
    # Escape @ inside JSON-LD (like "@context", "@type") to "@@context" so blade ignores them
    text = text.replace('"@', '"@@')
    return text

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

with open('resources/views/components/layouts/app.blade.php', 'w', encoding='utf-8') as f:
    f.write(app_html)

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

print("Split completed successfully!")
