import re
import os
import sys

filepath = r'D:\Dawnlord 2.0\nexagent.webflow.io\nexagent.webflow.io\index.html'
try:
    with open(filepath, 'r', encoding='utf-8') as f:
        html = f.read()
except Exception as e:
    print('Failed to read:', e)
    sys.exit(1)

# Replace branding (respect case as much as possible)
html = html.replace('NexAgent', 'LeadForge')
html = html.replace('Nexagent', 'LeadForge')
html = html.replace('nexagent', 'leadforge')

# Find head links and scripts
head_match = re.search(r'<head>(.*?)</head>', html, re.DOTALL | re.IGNORECASE)
head_content = head_match.group(1) if head_match else ''

head_links = re.findall(r'<link.*?>', head_content, re.IGNORECASE)
head_scripts = re.findall(r'<script.*?</script>', head_content, re.IGNORECASE | re.DOTALL)
head_styles = re.findall(r'<style.*?</style>', head_content, re.IGNORECASE | re.DOTALL)

# Find body content
body_match = re.search(r'<body.*?>(.*?)</body>', html, re.DOTALL | re.IGNORECASE)
body_content = body_match.group(1) if body_match else ''

# Clean up `<script>` inside `body_content` to convert to `next/script`
body_scripts_matches = re.finditer(r'<script(.*?)</script>', body_content, re.IGNORECASE | re.DOTALL)
body_scripts_jsx = []

# To avoid mutating body_content string indices, let's just use string replace for each match
for m in body_scripts_matches:
    script_str = m.group(0)
    src_match = re.search(r'src=[\"\'](.*?)[\"\']', script_str, re.IGNORECASE)
    if src_match:
        src = src_match.group(1)
        # remove it from HTML so Next.js script manages it
        body_content = body_content.replace(script_str, '')
        body_scripts_jsx.append(f'<Script src="{src}" strategy="lazyOnload" />')

# Escape backticks and dollars in head/styles so they fit in template literal
head_scripts_safe = chr(10).join(head_scripts).replace('`', r'\`').replace('$', r'\$')
head_styles_safe = chr(10).join(head_styles).replace('`', r'\`').replace('$', r'\$')
body_content_safe = body_content.replace('`', r'\`').replace('$', r'\$')

next_page = f'''"use client";

import React from "react";
import Script from "next/script";

export default function LandingPage() {{
  return (
    <>
      <head>
        {'\\n        '.join(head_links)}
        <div dangerouslySetInnerHTML={{{{ __html: `{head_scripts_safe}` }}}} />
        <div dangerouslySetInnerHTML={{{{ __html: `{head_styles_safe}` }}}} />
      </head>
      
      {{/* Inject the body */}}
      <div dangerouslySetInnerHTML={{{{ __html: `{body_content_safe}` }}}} />
      
      {{/* Inject bottom scripts via next/script */}}
      {'\\n      '.join(body_scripts_jsx)}
    </>
  );
}}
'''

out_path = r'd:\Ai\AntiGravity\Project_1.0\gmap\leadforge\src\app\page.tsx'
with open(out_path, 'w', encoding='utf-8') as f:
    f.write(next_page)
print('Done writing src/app/page.tsx!')
