
    UhM              	          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	m
Z
 ddlmZ ddlZej                            ej                            ej                            ej                            e                                        Z ej        e          Z G d de          Zdee	ee
f         z  d	e	ee
f         fd
Zde	ee
f         d	e	ee
f         fdZdede	ee
f         ded	efdZded	efdZi ddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1Zd2ed	efd3Zd4ed	efd5Zd4ed	efd6Z de	ee
f         d	efd7Z!d8e	ee
f         d	efd9Z"d:ed	efd;Z#d<e	ee
f         d	efd=Z$de	ee
f         d	efd>Z%ded	efd?Z&de	ee
f         d	efd@Z'de	ee
f         ded	efdAZ(dBedCed	dfdDZ)g dEZ*dS )Fz
Automated Tasks for Website Generation - Phase 1 (No AI Required)
Handles JSON parsing, template selection, and template setup automatically
    N)Path)DictAny)datetimec                       e Zd ZdZdS )AutomatedTaskErrorz*Custom exception for automated task errorsN)__name__
__module____qualname____doc__     J/var/www/html/web-builder-api.evdpl.com/src/services/website_data_utils.pyr   r      s        44Dr   r   
user_inputreturnc                    	 t          | t                    rt          j        |           n| ddg}fd|D             }|r%t	          dd                    |                     d                                                             dd                                                              dd                              dd                              d	d                              d
i                               di                               dd                              dd                              dd                              dg                               d                    di                               dd                                        d                    di                               dd                                        d                    di                               dd                    dt                              d                    dd                                                  d                    di                     d }t          
                    d!|d                     |S # t          j        $ r}t	          d"|           d#}~wt          $ r-}t          |t                    r t	          d$|           d#}~ww xY w)%z5Parse and validate JSON input for website generation.websiteNamewebsiteDescriptionc                 >    g | ]}                     |          |S r   get).0fielddatas     r   
<listcomp>z$parse_json_input.<locals>.<listcomp>    s(    TTTEDHHUOOT%TTTr   zMissing required fields: ,  restaurantPhonerestaurantEmailrestaurantAddressoperatingHours
socialUrlsfacebookUrlinstagramUrl
twitterUrlpagesprimaryColorcolorsprimary#2c3e50secondaryColor	secondary#3498dbaccentColoraccent#e74c3c)r)   r,   r/   
typographyselectedFontInterlogoInfowebsiteLogo)r   r   r   r   r    r!   r"   r#   r$   r%   r&   r(   r1   r4   z,Successfully parsed JSON input for website: zInvalid JSON format: NzError parsing JSON input: )
isinstancestrjsonloadsr   joinstripr   _normalize_font_keyloggerinfoJSONDecodeError	Exception)r   required_fieldsmissing_fieldswebsite_dataer   s        @r   parse_json_inputrE      s   )C)3J)D)DTtz*%%%* )*>?TTTT_TTT 	^$%\>AZAZ%\%\]]]  .4466"&((+?"D"D"J"J"L"L#xx(92>>#xx(92>>!%*=r!B!B"hh'7<<((<4488M266 HH^R88((<44XXgr**88NDHHXr4J4J4N4NyZc4d4dee!XX&628N8N8R8RS^`i8j8jkk((=$((8R2H2H2L2LXW`2a2abb  .dhh|TXXn^eEfEf.g.ghhTXXmR-H-HII'
 
, 	`<P]C^``aaa > > > !<!<!<=== C C Ca+,, 	 !Aa!A!ABBBCs$   J J$ $K?3KK?(K::K?rC   c                 t  K   	 | d         }|                      dg           }t          |          }t          t          j                            t          dd|                    }|j                            dd           |	                                r1t          j        |           t                              d|            |                    dd           t          || |           d{V }t          | |           d{V }dt!          |          |||t#          j                                                    | d	}t                              d
|            t                              d|            |S # t(          $ r-}t+          |t,                    r t-          d|           d}~ww xY w)z<Create website folder and HTML files for content generation.r   r&   	templates	generatedTparentsexist_okzRemoved existing directory: N)successdestination_pathsafe_folder_namehtml_files_createdlogo_files_copied	timestamprC   z%Successfully created website folder: zHTML files created: zError creating website folder: )r   _create_safe_folder_namer   ospathr:   PROJECT_ROOTparentmkdirexistsshutilrmtreer=   r>   _create_html_files_copy_logo_filesr7   r   now	isoformatr@   r6   r   )	rC   website_namer&   rN   	dest_pathrO   rP   setup_resultrD   s	            r   setup_templaterb   E   s     )H#M2  "-- 4LAAlKN^__``	 	td;;; 	DM)$$$KKByBBCCC 	t444 $6iu#U#UUUUUUU #3<"K"KKKKKKK  #I 0"4!2!1133(
 
 	GIGGHHH?+=??@@@ H H Ha+,, 	 !F1!F!FGGGHs   E;F   
F7
(F22F7r`   r&   c                 >  K   g }	 | dz  }d}t          ||           d{V  |                    t          |                     t                              d|j                    |S # t          $ r)}t                              d|            g cY d}~S d}~ww xY w)z6Create single index.html file for single-page website.z
index.htmlz<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Loading...</title>
</head>
<body>
    <p>Website is being generated...</p>
</body>
</html>NzCreated placeholder HTML file: zError creating HTML file: )_write_file_asyncappendr7   r=   r>   namer@   error)r`   rC   r&   rO   	page_filehtml_contentrD   s          r   r[   r[   r   s      ,	
  	<888888888!!#i..111FinFFGGG!!   5!55666						s   A"A) )
B3BBBr_   c                 R   | r|                                  sd}nd                    d |                                  D                       }t          j        dd|                                           }|                    dd          }t          j        dd|          }|                     d          }|                                }|sd}t          |          dk    r|d	d                             d          }t          j	                    
                    d
          }| d| S )zECreate a safe folder name from website name with improved formatting.websiter   c              3   J   K   | ]}|                                 s|d v |V  dS )) -_Nisalnumr   cs     r   	<genexpr>z+_create_safe_folder_name.<locals>.<genexpr>   s:      cc!qyy{{caSbNbNbANbNbNbNbccr   z\s+rm   ro   z_+2   Nz%Y_%m_%d_%H_%M_%S)r;   r:   resubreplacelowerlenrstripr   r]   strftime)r_   	safe_namerQ   s      r   rR   rR      s.    3|1133 3		 GGcc|'9'9';';ccccc	 F63	2288::	%%c3//	 F5#y11	 OOC((	 OO%%	  	"!I y>>B!#2#--c22I ''(;<<I%%)%%%r   playfairPlayfair Displayinterr3   robotoRobotoopensansz	Open SanslatoLato
montserrat
MontserratpoppinsPoppinsralewayRalewaynunitoNunitosourcezSource Sans ProdancingzDancing ScriptpacificoPacificosatisfySatisfy
greatvibeszGreat Vibesbebasz
Bebas Neue	righteous	Righteous
font_valuec                 "   | sdS t          |                                                                           }|t          v r|S d                    d |D                       }t                                          D ]n\  }}d                    d |                                D                       }||k    s.|                    |          s|                    |          s||v r|c S o|                                d         }|t          v r|S dS )zNormalize arbitrary font input to a canonical slug used across UI/backend.

    Tries to match known slugs first, then matches against known family names
    (e.g. 'Playfair Display' -> 'playfair'). Falls back to 'inter'.
    r   r   c              3   B   K   | ]}|                                 |V  d S Nrp   rr   s     r   rt   z&_normalize_font_key.<locals>.<genexpr>   s/      11QYY[[11111111r   c              3   B   K   | ]}|                                 |V  d S r   rp   rr   s     r   rt   z&_normalize_font_key.<locals>.<genexpr>   s/      DD		D1DDDDDDr   r   )r7   r;   ry   FONT_KEY_TO_FAMILYr:   items
startswithsplit)r   valnormkeyfamilyfam_normfirsts          r   r<   r<      s!     w
j//


!
!
'
'
)
)C
   
7711c11111D)//11  V77DDfllnnDDDDD8tx88H<O<OPT<U<UYaeiYiYiJJJ Zj IIKKNE"""7r   font_keyc                 V    t          |           }t                              |d          S )z,Convert font key to actual font family name.r   )r<   r   r   )r   r   s     r   _get_font_family_namer      s&    
h
'
'C!!#'9:::r   c                 8    h d}t          |           }||v rdndS )z%Get appropriate fallback font family.>   loraptserifr~   	cormorantmerriweatherserifz
sans-serif)r<   )r   
serif_keysr   s      r   _get_font_fallbackr      s.    MMMJ
h
'
'CZ''77\9r   c                    	 |                      dd          }|                      dd          }|                      dd          }|                      dd          }|                      dd          }t          |                      di                     }t          |                      di                     }t          |           }t	          |                      d	g                     }	t          |           }
d
dg}dg}|r|                    d|            |                    d|            |                    dt          j                    j	                    |
                                r|                    d|            |                    d           |                    |           |                    d           dg}d}|
                                r|                    d|            d}|
                                r|                    d|            d}|
                                r|                    d|            d}|r*|                    |           |                    d           |
                                r|                    d|dg           |
                                r|                    d|dg           |                    d|
g           d                    |          }t                              d|            |S # t          $ r4}t                              d|            t#          d|           d}~ww xY w)z
    Format website data into AI prompt for website generation.
    
    Args:
        website_data: Parsed website data from JSON input
        
    Returns:
        Formatted prompt string for AI workflow
    r   r   r   r   r   r    r!   r4   r&   zJGenerate a website for a restaurant based on the following specifications:zGeneral Information:zLogo: zWebsite Name: zYear: zDescription: zType: restaurantzContact Information:FzPhone: TzEmail: z	Address: zOperating Hours:zSocial Media:zDesign & Branding:
z6Successfully formatted website data to AI prompt for: z!Error formatting website prompt: N)r   _format_operating_hours_format_logo_info_format_social_media_format_pages_format_design_infore   r   r]   yearr;   extendr:   r=   r>   r@   rg   r   )rC   r_   descriptionphoneemailaddressoperating_hours	logo_infosocial_mediar&   design_infoprompt_sectionsgeneral_infocontact_infocontact_addedpromptrD   s                    r   format_website_promptr      s   MJ#''r::"&&';R@@  !2B77  !2B77""#6;; 2,2B2BCSUW2X2XYY &l&6&6z2&F&FGG	 ,L99 l..w;;<< *,77 hikl // 	6 4 4 4555;\;;<<<:X\^^%8::;;; 	? = = =>>>.///|,,,r""" //;;== 	! 1% 1 1222 M;;== 	! 1% 1 1222 M==?? 	! 5G 5 5666 M 	'""<000""2&&&   "" 	N""$6#LMMM  	H""O\2#FGGG 	 4kBCCC?++[\[[\\\ J J J<<<=== !HQ!H!HIIIJs   L$L' '
M%1/M  M%r   c                 b   | sdS g d}g }d}|t          |          k     r||         }|                     |i           }|                    dd          s1|                    |                                 d           |dz  }nt	          |                    dd	                    }t	          |                    d
d                    }| d| }|}	t          |dz   t          |                    D ]}
||
         }|                     |i           }|                    dd          s nXt	          |                    dd	                    }t	          |                    d
d                    }| d| }||k    r n|
}	|	|k    r-|                    |                                 d|            nK|                                }||	                                         }|                    | d| d|            |	dz   }|t          |          k     d                    |          S )z?Format operating hours for DeepSite prompt with smart grouping.r   )mondaytuesday	wednesdaythursdayfridaysaturdaysundayr   isOpenFz: Closed   openz09:00closez22:00z - : r   )rz   r   re   
capitalize_convert_24h_to_12hranger:   )r   days
hours_listidayday_data	open_time
close_timecurrent_hours	group_endjnext_daynext_day_datanext_open_timenext_close_time
next_hours	first_daylast_days                     r   r   r   C  sh    rYYYDJ	A
c$ii--1g"&&sB//||He,, (	!1!1;;;<<<FAA ,HLL,I,IJJI,X\\'7-K-KLLJ(99Z99M I1q5#d)),,  7 / 3 3Hb A A$((599 E!4]5F5Fvw5W5W!X!X"5m6G6GQX6Y6Y"Z"Z .DD?DD
..E		 A~~!!S^^%5%5"H"H"H"HIIII  NN,,		?5577!!Y"N"N8"N"N}"N"NOOOAAY c$ii--\ 99Z   r   time_24hc                     	 |                      d          \  }}t          |          }t          |          }|dk    rd|ddS |dk     r	| d|ddS |dk    rd|ddS |dz
   d|ddS #  | cY S xY w)z'Convert 24-hour time to 12-hour format.:r   z12:02dz AM   z PM)r   int)r   hourminutes      r   r   r   |  s    ~~c**f4yyV199((((((BYY,,V,,,,,RZZ((((((Ri11&11111s   AA- A- A- !A- -A3r   c                 r    | sdS |                      d          p|                      dd          }|sdS d| S )z,Format logo information for DeepSite prompt.r   filenameserverFilenamez
asset/img/r   )r   r   s     r   r   r     sS     r }}Z((OIMM:JB,O,OH r #"""r   c                 t   |                      di           }|                     d|                      dd                    }|                     d|                      dd                    }|                     d|                      dd                    }g }|r,|                                r|                    d	|            |r,|                                r|                    d
|            |r,|                                r|                    d|            |rd                    |          ndS )z-Format social media URLs for DeepSite prompt.r"   facebookr#   r   	instagramr$   twitterr%   z
Facebook: zInstagram: z	Twitter: r   )r   r;   re   r:   )rC   social_urlsr   r   r   liness         r   r   r     s;   ""<44Kz<+;+;M2+N+NOOH\-=-=nb-Q-QRRIooi)9)9,)K)KLLGE .HNN$$ .,(,,--- 0Y__&& 0.9../// ,7==?? ,***+++$,499U",r   c                 4    | sdS d                     |           S )z&Format pages list for DeepSite prompt.zhome, about, contactr   )r:   )r&   s    r   r   r     s"     &%%99Ur   c           
         |                      di           }|                      dd          }t          |          }d|                     dd           d|                     dd	           d
|                     dd           d| d| 
S )z;Format design and branding information for DeepSite prompt.r(   r1   r   zPrimary Color: r)   r*   z
Secondary Color: r,   r-   z
Accent Color: r/   r0   z
Typography: z
Selected Font: )r   r   )rC   r(   r1   font_familys       r   r   r     s    h++F!!,88J (
33K vzz)Y??    **[)44   zz(I..        	     r   c                   K   g }	 |                      di           }|st                              d           |S |                     d          p|                     dd          }|st                              d           |S |dz  dz  }|                    d	d	
           t	          t
                    j        j        j        }|dz  dz  |z  }|                                r||z  }t          j	        ||           |
                    t          |                     t                              d|            	 |                                 t                              d|            n7# t          $ r*}	t                              d| d|	            Y d}	~	nd}	~	ww xY w|S # t          $ r)}
t                              d|
            |cY d}
~
S d}
~
ww xY w)a  
    Copy logo files to asset/img/ directory and delete from uploads after successful copy.
    
    Args:
        website_data: Website data containing logo information
        dest_path: Destination path for the website
        
    Returns:
        List of copied logo files
    r4   zNo logo file to copyr   r   r   zNo logo filename foundassetimgTrI   uploadslogoszCopied logo file: z'Deleted source logo file from uploads: z"Failed to delete source logo file r   NzError copying logo files: )r   r=   r>   rW   r   __file__rV   rX   rY   copy2re   r7   unlinkr@   rg   )rC   r`   rP   r   logo_filenameasset_img_dirproject_rootsource_logo_pathdest_logo_pathdelete_errorrD   s              r   r\   r\     s3      &! $$Z44	 	%KK.///$$ "j11XY]]CSUW5X5X 	%KK0111$$ "G+e3D4888 H~~,3:')3g=M""$$ 	c*]:NL)>:::$$S%8%8999KK<]<<===c '')))UmUUVVVV c c ca-aaS_aabbbbbbbbc !  ! ! !5!55666       !sT   3F) AF) B:F) >1E0 /F) 0
F$: FF) F$$F) )
G3GGG	file_pathcontentc                    K   t          j        | dd          4 d{V }|                    |           d{V  ddd          d{V  dS # 1 d{V swxY w Y   dS )z%Write content to file asynchronously.wzutf-8)encodingN)aiofilesr   write)r  r  fs      r   rd   rd     s      }Yg>>>       !ggg                             s   A
AA)rE   rb   r   r\   r   )+r   r8   loggingrS   rY   rv   pathlibr   typingr   r   r   r  rT   dirnameabspathr  rU   	getLoggerr	   r=   r@   r   r7   rE   rb   listr[   rR   r   r<   r   r   r   r   r   r   r   r   r   r\   rd   __all__r   r   r   <module>r     s      				  				                      wrwrwrwx?X?X/Y/YZZ[[		8	$	$	 	 	 	 	 	 	 	+CtCH~!5 +C$sCx. +C +C +C +CZ+HtCH~ +H$sCx. +H +H +H +HZ DcN SW \`    > &3  &3  &  &  &  &F"W h 	
 F , y y h   
 y - \  ! &C C    0;C ;C ; ; ; ;
: : : : : :WJS#X WJ3 WJ WJ WJ WJr7!T#s(^ 7! 7! 7! 7! 7!r# #    $#c3h #C # # # #-tCH~ -# - - - -$ #     d38n          3!c3h 3!D 3!T 3! 3! 3! 3!jt c d      r   