import os
import re
import urllib.request
from urllib.parse import urlparse, urljoin
import sys

# We no longer use a WordPress-style folder layout locally. Anything scraped
# under /wp-content/... or /wp-includes/... on the live site is downloaded
# into our own /assets/... structure instead:
#   wp-content/uploads  -> assets/uploads
#   wp-content/themes   -> assets/themes
#   wp-content/plugins  -> assets/plugins
#   wp-content/cache    -> assets/cache
#   wp-includes/...     -> assets/core/...
def to_local_rel_path(remote_path):
    remote_path = remote_path.lstrip('/')
    if remote_path.startswith('wp-content/'):
        return 'assets/' + remote_path[len('wp-content/'):]
    if remote_path.startswith('wp-includes/'):
        return 'assets/core/' + remote_path[len('wp-includes/'):]
    return remote_path

def to_local_url_path(remote_path):
    # Same mapping, but for rewriting HTML/CSS references (always with a
    # leading slash, since these are absolute site-root paths).
    remote_path = remote_path.lstrip('/')
    if remote_path.startswith('wp-content/'):
        return '/assets/' + remote_path[len('wp-content/'):]
    if remote_path.startswith('wp-includes/'):
        return '/assets/core/' + remote_path[len('wp-includes/'):]
    return '/' + remote_path

def download_file(url, local_path):
    if not os.path.exists(local_path):
        os.makedirs(os.path.dirname(local_path), exist_ok=True)
        try:
            req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
            with urllib.request.urlopen(req, timeout=10) as response, open(local_path, 'wb') as out_file:
                out_file.write(response.read())
            print(f"Downloaded: {url}")
            sys.stdout.flush()
            return True
        except Exception as e:
            print(f"Failed: {url} -> {e}")
            sys.stdout.flush()
            return False
    else:
        print(f"Already exists: {url}")
        sys.stdout.flush()
    return True

def process_css(file_path, base_url):
    if not os.path.exists(file_path): return
    with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
        css = f.read()

    urls = re.findall(r'url\([\'"]?(.*?)[\'"]?\)', css)
    for u in urls:
        if u.startswith('data:') or u.startswith('#') or u == '': continue

        full_url = urljoin(base_url, u)
        if 'sarabeauty.ae' in full_url:
            parsed = urlparse(full_url)
            local_rel_path = to_local_rel_path(parsed.path)
            local_abs_path = os.path.join('public', local_rel_path.replace('/', os.sep))

            download_file(full_url, local_abs_path)

def extract_and_download(html_file):
    with open(html_file, 'r', encoding='utf-8') as f:
        html = f.read()

    urls = re.findall(r'https://sarabeauty\.ae/(wp-content[^"\'\s),]+|wp-includes[^"\'\s),]+)', html)

    for u in set(urls):
        url = 'https://sarabeauty.ae/' + u
        parsed_url = urlparse(url)
        local_rel_path = to_local_rel_path(parsed_url.path)
        local_abs_path = os.path.join('public', local_rel_path.replace('/', os.sep))

        if download_file(url, local_abs_path):
            if url.endswith('.css') or parsed_url.path.endswith('.css'):
                process_css(local_abs_path, url)
                # Rewrite the CSS file's own remote references to local paths
                with open(local_abs_path, 'r', encoding='utf-8', errors='ignore') as cf:
                    css_text = cf.read()
                new_css_text = re.sub(
                    r'https://sarabeauty\.ae/(wp-content|wp-includes)(/[^\s"\')]*)',
                    lambda m: to_local_url_path(m.group(1) + m.group(2)),
                    css_text,
                )
                if new_css_text != css_text:
                    with open(local_abs_path, 'w', encoding='utf-8') as cf:
                        cf.write(new_css_text)

    html = re.sub(
        r'https://sarabeauty\.ae/(wp-content|wp-includes)(/[^\s"\')]*)',
        lambda m: to_local_url_path(m.group(1) + m.group(2)),
        html,
    )

    with open(html_file, 'w', encoding='utf-8') as f:
        f.write(html)

print("Starting download...")
sys.stdout.flush()
import glob

files_to_process = [
    'resources/views/components/layouts/app.blade.php',
    'resources/views/home.blade.php',
    'resources/views/about.blade.php'
]
files_to_process.extend(glob.glob('resources/views/services/*.blade.php'))
files_to_process.extend(glob.glob('resources/views/pages/*.blade.php'))
files_to_process.extend(glob.glob('resources/views/pages/blogs/*.blade.php'))
files_to_process.extend(glob.glob('resources/views/blog-posts/*.blade.php'))

for file_path in files_to_process:
    extract_and_download(file_path)
print("All assets downloaded and HTML updated!")
sys.stdout.flush()
