
    N&i8?                     j   d Z ddlZddlZddlZddlZddlZddlmZ ddlm	Z	  ej                  d      Zde	e   fdZdZ	 	 	 d+d	ed
ededededededefdZd,dedede	e   fdZdedefdZdededefdZ	 	 	 	 	 	 d-d	ed
ededededededede	e   fdZ	 d.d
edededededefdZedk(  r ej,                  ej.                  d       dZ eeddd d!d"#      ZerL ed$      Zej6                  j9                  d%d%&       ej;                  e        ed'e d( ee       d)       y ed*       yy)/u6  
Genesis Clone Pipeline — AI Reconstruction Module
==================================================
Uses Gemini Flash to reconstruct a cloned website as clean, modern HTML
with Tailwind CSS, mobile-first design, and Genesis chatbot widget.

Model: google.genai (new SDK) with google-generativeai fallback.
    N)Path)Optionalzclone_pipeline.reconstructorreturnc                      dD ]'  } t         j                  j                  |       }|s%|c S  	 t        j                  j                  dd       ddlm}  |       S # t        $ r Y yw xY w)z7Resolve Gemini API key from environment or secrets.env.)GEMINI_API_KEYGOOGLE_API_KEYGOOGLE_GEMINI_API_KEYr   z/mnt/e/genesis-system/core)get_gemini_api_keyN)	osenvirongetsyspathinsertsecrets_loaderr
   	Exception)key_namevalr
   s      =/mnt/e/genesis-system/scripts/clone_pipeline/reconstructor.py_get_gemini_api_keyr      sg     R jjnnX&J785!## s   ,A 	A'&A'a  You are a world-class web developer specialising in rebuilding
Australian tradie and small business websites. You take existing website content and transform it
into a modern, high-performance, mobile-first HTML page that will rank well on Google and convert
visitors into leads.

Your output must be:
- A single, complete, standalone HTML file
- Mobile-first responsive using Tailwind CSS (CDN)
- Fast loading (no heavy dependencies except Tailwind CDN)
- Professional and trustworthy in appearance
- Optimised for conversions (clear CTAs, phone number prominent)
- Include proper SEO meta tags and Open Graph tags
- Include local business schema markup (JSON-LD)

Always return ONLY the complete HTML file. No explanations. No markdown code blocks.
Just pure HTML starting with <!DOCTYPE html>.contentbusiness_nameservicesphonelocationurlwidget_snippetc                     d}t        |       |kD  r| d| dz   } d| d|  d| d|r|nd d	|r|nd d
|r|nd d| d| d| d| d| d|r|nd d| d}|S )z0Build the Gemini prompt for site reconstruction.i.  Nz'

[Content truncated for processing...]zYou are rebuilding z,'s website. Here is their current content:

z%

BUSINESS DETAILS:
- Business Name: z
- Services: zSee content abovez

- Phone: z
- Location: z
- Original URL: a  

Create a modern, mobile-first HTML page with:

1. DOCTYPE html, head with title, meta description, Open Graph tags, viewport meta
2. Tailwind CSS CDN: <script src="https://cdn.tailwindcss.com"></script>
3. Hero section with:
   - Business name as H1
   - Clear value proposition subtitle
   - Main service offering
   - Prominent phone number as a clickable link (tel: protocol)
   - Strong call-to-action button ("Call Now" or "Get a Free Quote")
4. Services section:
   - Grid of their actual services from the content
   - Icons or emoji to make it scannable
5. Why Choose Us / Trust section:
   - Years in business if mentioned
   - Service area
   - Key differentiators (licensed, insured, etc.)
   - 2-3 trust badges/icons
6. Testimonials section (use 2-3 realistic placeholder testimonials in their industry style)
7. Contact section:
   - Phone number (click to call)
   - Contact form: name, phone, service needed, preferred time, message
   - Service area / location
8. Footer with:
   - Business name
   - Phone
   - Copyright z
9. Local Business schema JSON-LD in head:
   {
     "@context": "https://schema.org",
     "@type": "LocalBusiness",
     "name": "z",
     "telephone": "zA",
     "address": { "@type": "PostalAddress", "addressRegion": "z[" }
   }
10. Floating "Chat with us" button (bottom right corner) with this EXACT snippet:
z5<!-- Genesis chatbot widget will be injected here -->a  

DESIGN REQUIREMENTS:
- Colour scheme: Professional blues/greys for trade services, or match industry colours from content
- Typography: Clean sans-serif (system fonts or Google Fonts Inter)
- Australian spelling and tone (e.g., "colour", "favour", "licence")
- All phone numbers as tel: links for mobile click-to-call
- Sticky header with phone number visible at all times
- Mobile hamburger menu
- Smooth scroll to sections

SEO REQUIREMENTS:
- Title tag: "aR   | [Main Service] | [Location]"
- Meta description: 155 chars max, include service + location + phone
- H1: Business name (only one H1)
- H2: Section headings
- Alt text on all images (use placeholder images from https://placehold.co/)

Return ONLY the complete HTML file. No markdown. No code blocks. Start directly with <!DOCTYPE html>.)len)	r   r   r   r   r   r   r   max_content_charsprompts	            r   _build_reconstruction_promptr"   A   s     
7|'',,-0[[$]O 4	 
   !!X':; <
%1	2 3!X':; < 8  
 o 7 @@Hz J "'^ _ ` o fwAiFF M    r!   modelc           	      p   t               }|st        j                  d       y	 ddlm} ddlm} |j                  |      }t        j                  d| d       |j                  j                  || |j                  t        dd	
            }|j                  }|r$t        j                  dt        |       d       |S 	 	 ddl}	|	j%                         5  |	j'                  d       ddlm}
 ddd       
j-                  |       	 |
j/                  |t              }t        j                  d       |j                  | |
j1                  dd	            }|j                  }|r$t        j                  dt        |       d       |S 	 y# t        $ r t        j                  d       Y t        $ r$}t        j!                  d| d       Y d}~d}~ww xY w# 1 sw Y   xY w# t        $ r |
j/                  d      }Y w xY w# t        $ r"}t        j                  d|        Y d}~yd}~ww xY w)z~
    Call Gemini API to reconstruct the website.
    Tries new google.genai SDK first, falls back to google.generativeai.
    zN[Reconstructor] No Gemini API key found. Set GEMINI_API_KEY or GOOGLE_API_KEY.Nr   )types)api_keyz [Reconstructor] Calling Gemini (z) via google.genai SDK...i    g333333?)system_instructionmax_output_tokenstemperature)r$   contentsconfigz[Reconstructor] Received z chars from Geminiz@[Reconstructor] google.genai not available, trying legacy SDK...z%[Reconstructor] google.genai failed: z, trying legacy SDK...ignore)
model_namer(   zgemini-1.5-flash)r.   z0[Reconstructor] Calling Gemini via legacy SDK...)r)   r*   )generation_configz chars (legacy SDK)z([Reconstructor] Legacy SDK also failed: )r   loggererrorgoogle.genaigenair&   Clientinfomodelsgenerate_contentGenerateContentConfigRECONSTRUCTION_SYSTEM_PROMPTtextr   ImportErrorr   warningwarningscatch_warningssimplefiltergoogle.generativeaigenerativeai	configureGenerativeModelGenerationConfig)r!   r$   r'   r3   r&   clientresponser:   er=   genai_legacy	model_objs               r   _call_geminirJ      s?   
 "#GefZ$&g.6ug=VWX==11..#?"& /  2 
 }}KK3CI;>PQRK !E$$& 	7!!(+6	7 	w/	T$44 #? 5 I 	FH--*;;"& <  . 
 }}KK3CI;>QRSK  S  XVW Z>qcAWXYYZ	7 	7  	T$44@R4SI	T$  E?sCDDEss   BF H
 G/H
 
G) !A*H
 G.G6GGG&"H
 )HH
 HH
 
	H5H00H5rawc                 ~   | j                         } | j                  d      r| dd } n| j                  d      r| dd } | j                  d      r| dd } | j                         } | j                         j	                  d      }|dkD  r| |d } | S |d	k(  r)| j                         j	                  d
      }|dkD  r| |d } | S )z|
    Strip any markdown code block wrappers that Gemini sometimes adds.
    Ensures output starts with <!DOCTYPE html>.
    z```html   Nz```   z	<!doctyper   z<html)strip
startswithendswithlowerfind)rK   doctype_idxhtml_idxs      r   _clean_html_outputrX      s    
 ))+C ~~i !"g		!"g
||E#2h
))+C ))+"";/KQ+, J 
	99;##G,a<hi.CJr#   htmlc                     |s| S d| v sd| v r| S | j                         j                  d      }|dk7  r| d| dz   |z   dz   | |d z   } | S | dz   |z   } | S )zR
    Inject the chatbot widget snippet before </body> if not already present.
    zgenesis-chat-widgetGenesisChatz</body>rP   N
)rT   rfind)rY   r   
body_closes      r   _inject_widgetr_     s     $(= ##I.JRKZ 4'.84?$z{BSS K d{^+Kr#   c           	         | st         j                  d       y|sd}t         j                  d       t         j                  d|        t	        | ||||||      }t        ||      }	|	s$t         j                  d       t        |||||      S t        |	      }
t        |
|      }
t         j                  d	t        |
       d
       |
S )a  
    Reconstruct a business website as clean HTML using Gemini Flash.

    Args:
        content: Extracted markdown/text content from the original site
        business_name: Name of the business
        services: Comma-separated list of services
        phone: Business phone number
        location: City/region
        url: Original URL (for reference)
        widget_snippet: HTML snippet for Genesis chatbot widget
        model: Gemini model to use

    Returns:
        Complete HTML string, or None if reconstruction fails.
    z6[Reconstructor] No content provided for reconstructionNzYour Businessz<[Reconstructor] No business name provided, using placeholderz)[Reconstructor] Reconstructing site for: )r   r   r   r   r   r   r   )r$   z*[Reconstructor] Gemini returned no contentz[Reconstructor] Final HTML: z chars)
r0   r1   r<   r5   r"   rJ   _generate_fallback_htmlrX   r_   r   )r   r   r   r   r   r   r   r$   r!   raw_htmlrY   s              r   reconstruct_siterc   %  s    4 MN'UV
KK;M?KL *#%F F%0HAB&}hxQ_`` h'D$/D
KK.s4yk@AKr#   c                    t         j                  d       |r>|j                  d      D cg c]#  }|j                         s|j                         % c}ndg}dj	                  d |dd D              }dj	                  g d	|  d
| d|  d|r|d   nd d| d| d|  d| d| d|  d| d| d| d| d| d| d|  d| d| d      S c c}w )zR
    Generate a minimal but functional HTML page as fallback if Gemini fails.
    z1[Reconstructor] Generating fallback HTML template,zOur Servicesr\   c              3   (   K   | ]
  }d | d  yw)z^<div class="bg-white rounded-lg p-6 shadow-sm border"><h3 class="font-semibold text-gray-800">z</h3></div>N ).0ss     r   	<genexpr>z*_generate_fallback_html.<locals>.<genexpr>o  s%       iijhkkvws   N    z<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>z | Professional Services | z/</title>
    <meta name="description" content="z - Professional r   r   z in z. Call aH   today.">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50 font-sans">
    <!-- Header -->
    <header class="bg-blue-900 text-white shadow-lg sticky top-0 z-50">
        <div class="max-w-6xl mx-auto px-4 py-4 flex justify-between items-center">
            <h1 class="text-xl font-bold">z</h1>
            <a href="tel:zw" class="bg-yellow-400 text-blue-900 font-bold px-4 py-2 rounded hover:bg-yellow-300 transition">
                Call z
            </a>
        </div>
    </header>

    <!-- Hero -->
    <section class="bg-gradient-to-br from-blue-900 to-blue-700 text-white py-20">
        <div class="max-w-4xl mx-auto px-4 text-center">
            <h2 class="text-4xl font-bold mb-4">z*</h2>
            <p class="text-xl mb-2">zu</p>
            <p class="text-lg opacity-90 mb-8">Professional services you can trust</p>
            <a href="tel:z" class="bg-yellow-400 text-blue-900 font-bold text-xl px-8 py-4 rounded-lg hover:bg-yellow-300 transition inline-block">
                Call Now: aW  
            </a>
        </div>
    </section>

    <!-- Services -->
    <section class="py-16 bg-gray-50">
        <div class="max-w-6xl mx-auto px-4">
            <h2 class="text-3xl font-bold text-center text-gray-800 mb-10">Our Services</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                a_  
            </div>
        </div>
    </section>

    <!-- Contact -->
    <section class="py-16 bg-blue-900 text-white">
        <div class="max-w-2xl mx-auto px-4 text-center">
            <h2 class="text-3xl font-bold mb-6">Get In Touch</h2>
            <p class="text-xl mb-6">Ready to get started? Contact us today.</p>
            <a href="tel:z" class="bg-yellow-400 text-blue-900 font-bold text-2xl px-10 py-5 rounded-lg hover:bg-yellow-300 transition inline-block">
                z
            </a>
        </div>
    </section>

    <!-- Footer -->
    <footer class="bg-gray-800 text-gray-400 py-8 text-center">
        <p>&copy; z. z\.</p>
        <p class="mt-1 text-sm">Website enhanced by Genesis AI</p>
    </footer>

    z
</body>
</html>)r0   r5   splitrQ   join)r   r   r   r   r   ri   services_listservices_htmls           r   ra   ra   c  s`    KKCDMUs(;I1qwwyQWWYI\j[kMII r" M
= =  =
 ?=
 6=
 7?Z=
@'= (5o= 6F= [hmTUFVmwEx= y}= ~F  }G= GN= OT  NU=U+= ,9/=:=  =!= W=1=. 2?/=.@%/=0 &.J1=0/1=4  5=4!5=6 !'7=6
"7=J K=J
 K=^  _=^!_=` a=`a=n !/o=n "$o=n %-:o=n.o=v w=vw= = Js   C-C-__main__z%(levelname)s %(message)s)levelformataF  
    Bob's Plumbing - Brisbane's trusted plumbers since 2005.
    Services: Emergency plumbing, blocked drains, hot water systems, gas fitting, bathroom renovations.
    Available 24/7 for emergencies.
    Service areas: Brisbane Northside, Southside, Ipswich.
    Call us: 07 3456 7890
    Licensed and insured plumbers.
    zBob's Plumbingz:Emergency Plumbing, Blocked Drains, Hot Water, Gas Fittingz07 3456 7890Brisbanezhttps://example.com)r   r   r   r   r   r   zI/mnt/e/genesis-system/scripts/clone_pipeline/output/test_reconstruct.htmlT)parentsexist_okzOutput saved: z (z chars)zReconstruction failed)rl   rl   rl   )gemini-2.5-flash)rl   rl   rl   rl   rl   rw   )rl   ) __doc__r   r   loggingjsonrepathlibr   typingr   	getLoggerr0   strr   r9   r"   rJ   rX   r_   rc   ra   __name__basicConfigINFOtest_contentrY   outparentmkdir
write_textprintr   rg   r#   r   <module>r      sb   
 
   	  			9	:Xc] . 1 . SSS S 	S
 S 
S S 	StK KS K(3- KdC C > c c 8 #;;; ; 	;
 ; 
; ; ; c];F NNN N 	N
 N 	Nj zGgll3NOL &M!D ^_

5tse2c$i[89%&7 r#   