
    "8i?                        d dl mZmZ d dlmZ d dlmZmZ d dlm	Z	 d dl
mZmZ d dlmZ d dlmZ d dlmZmZ d d	lmZ d d
lmZ d dlmZ d dlmZ d dlmZ d dlmZm Z m!Z!m"Z" d dl#m$Z$  ee%      Z& e       Z' ee'jP                        Z)e)jU                  dd        ee'jV                        Z,e,jU                  dd        ee'jZ                        Z.e.jU                  dd        G d d      Z/y)    )OptionalList)Path)HTTPExceptionstatus)run_in_threadpool)Sessionselect)setup_logger)get_settings)ERR_NOT_FOUNDERR_FIELD_UPDATE)ProjectMaster)ProductImage)ProjectRepository)ProductImageRepository)ProductTemplateRepository)validate_overlay_filevalidate_logo_filesave_upload_file_streamedsafe_delete)generate_final_imageT)parentsexist_okc                       e Zd ZdZededededefd       Zedede	de	d	e
e   d
edefd       Zedede	fd       Zede	de
e   de
e   defd       Zedede	fd       Zedede	fd       Zy)ProjectServicez!High-level project orchestration.project_nameclient_namesessionreturnc           
        K   	 t        |       	 d}|r$	 t        |       t        |t               d{   }t        |t               d{   }t        | |t        |      |rt        |      nd      }	t        j                  ||	      }	t        j                  |      }
|
s/t        t!        |             t        t        j"                  d      g }t!        |      g}	 |
D ]  }	 t%        t&        |j(                  t        |      t        t*              |rt        |      nd       d{   }|j5                  t!        |             t7        |	j0                  |j0                  t        |      	      }t9        j:                  ||      }|j5                  |        	 |j?                  |	       |	S # t        $ r)}t        t        j                  t        |            d}~ww xY w# t        $ r}t        dt        |            d}~ww xY w7 # t        $ r)}t        t        j                  t        |            d}~ww xY w7 7 # t        $ rN}t,        j/                  d|j0                         t        t        j2                  d|j0                         |d}~ww xY w# t        $ rO |D ]  }t        |        	 t        j<                  ||	        # t        $ r t,        j/                  d
       Y  w xY ww xY ww)z
        Create a project, process overlay against all active product templates,
        and persist ProductImage rows for each generated image.
        status_codedetailNi  )r   r   overlay_image_pathlogo_image_pathzNo product templates available.	logo_pathz(Failed to generate image for template %szFailed to process template project_master_idproduct_template_idfinal_image_pathz3Failed to rollback project after generation failure) r   	Exceptionr   r   HTTP_400_BAD_REQUESTstrr   r   LOGO_OVERLAYSTORAGE_OVERLAYr   r   create_projectr   list_allr   r   HTTP_404_NOT_FOUNDr   r   	file_pathSTORAGE_FINALlogger	exceptionidHTTP_500_INTERNAL_SERVER_ERRORappendr   r   createsoft_delete_projectrefresh)r   r   overlay_file	logo_filecurrent_userr   excr(   overlay_pathproject	templatescreated_images	tmp_pathstplfinal_path_strgen_excentryps                     N/var/www/html/story-book/Story-Book-python-api/app/services/project_service.pyr2   zProjectService.create_project"   s    	Z!,/

	ZIJ&y1 #<I|"TT	
 7|_UU  %#"<0.7C	NT	
 $227GD .66w?	\*+F,E,ENopp,'(	#	 W+<,L)M*4=#i.4, &N   n!56 %&-jj(+%(%8
 /55guE%%e,/ !J 	 ]  	ZF,G,GPSTWPXYY	Z ! J'CCIIJ U 	ZF,G,GPSTWPXYY	Z V4& ! W$$%OQTQWQWX'F4Y4Yd  AD  AG  AG  @H  cI  J  PW  WW  		A X!55gwG   X  !VWX		s   L F1 H G& H HH L IBL  J% &AI*I+I/A.J% L 1	G#:$GG##L &	H
/HH

H 	I$H==IL I	J"A	JJ""J% %K=KK=K96K=8K99K==L pagelimitsearchsort_byorderc                 8    t        j                  | |||||      S )Nr   rN   rO   rP   rQ   rR   )r   list_advancedrT   s         rM   list_projectszProjectService.list_projects   s'     ..
 	
    
project_idc                 $   t        j                  | |      }|r|j                  rt        t        j
                  t              t        j                  | |      }g }|D ].  \  }}|j                  |j                  |j                  |d       0 ||fS )N)r9   r,   product_template)r   get_project
is_deletedr   r   r4   r   r   list_with_templater;   r9   r,   )r   rX   rD   rowsimagesimgrH   s          rM   get_project_detailz!ProjectService.get_project_detail   s    #//D',, 9 9=II%88*M HCMMff$'$8$8$'   rW   dbc           
        K   t         j                  j                  j                         }t        j                  ||       }|r|j
                  rt        t        j                  t              t        |||g      st        t        j                  t              |r||_        |r||_        |sB|j                  |       |j!                          |j#                  |       dd|j$                  dS 	 t'        |       d}
	 |r#t-        |       t/        |t0               d{   }
t3        t/        |t                d{         j                         }t+        |j5                  |            }t7        j8                  ||       }|st;        |       t        dd      |j<                  r$t3        ||j<                        j                         nd}i }|D ]6  }	 t3        ||j>                        j                         }|||j@                  <   8 |D ci c]  }|j@                  | }}tC        |jE                               }tG        jH                  ||      }g }g }	 |D ]  }tK        tL        |jN                  t+        |      t+        tP              t+        |r|
n|jR                               d{   }t3        |      j                         }t+        |j5                  |            }|jU                  |       |j$                  |v r(||j$                     }||_        |j                  |       tW        |j$                  |j$                  |      }|jU                  |       |j                  |        |jY                          	 |
r't+        t3        |
      j                               |_)        ||_        |j                  |       |j!                          |j#                  |       |jc                         D ]  }|j#                  |        |D ]  }|j#                  |        	 	 |D ch c]  }|j                          }}|je                         D ]%  \  }} 	 | jg                         r| |vrt;        |        ' 	 |r	 t;        |       dd|j$                  dS # t(        $ r(}	t        t        j                  t+        |	            d}	~	ww xY w7 # t(        $ r(}	t        t        j                  t+        |	            d}	~	ww xY w7 # t(        $ r Y Bw xY wc c}w 7 p# t(        $ ra}	tZ        j]                  d	       |j_                          |D ]  }t;        |        t;        |       t        t        j`                  d
      d}	~	ww xY w# t(        $ rS}	tZ        j]                  d       |j_                          |D ]  }t;        |        t;        |       t        dd      d}	~	ww xY wc c}w # t(        $ r tZ        j]                  d|        Y w xY w# t(        $ r tZ        j]                  d       Y w xY w# t(        $ r tZ        j]                  d|       Y w xY ww)a*  
        Update project metadata and optionally regenerate final images when overlay changes.
        Handles template-count changes:
        - If new templates appear -> INSERT new rows
        - Else -> UPDATE existing rows only
        Ensures full rollback and file cleanup on failure.
        TzProject updated successfully.)successmessagerX   N  z'No image mapping found for this projectr'   r)   z!Regeneration failed; rolling backz)Project update failed during regenerationzCommit failed; rolling back  z#Failed to commit regenerated imagesz$Failed to delete old final image: %sz)Unexpected error during old-image cleanupz Failed to delete old overlay: %s)4r1   parentresolver   r[   r\   r   r   r4   r   anyr.   r   r   r   addcommitr>   r9   r   r-   r/   r   r   r0   r   relative_tor   list_by_projectr   r%   r,   r+   listkeysr   list_by_idsr   r   r5   r6   r&   r;   r   flushr7   r8   rollbackr:   valuesitemsexists)!rX   r   r   r?   r@   rA   rb   STORAGE_ROOTrD   rB   new_logo_pathnew_overlay_absnew_overlay_relexisting_rowsold_overlay_absold_final_abs_maprowabs_pathexisting_maptemplate_idsrE   new_final_abs_listcreated_rowsrH   rI   	final_abs	final_relnew_rowfrL   new_final_settpl_idold_abss!                                    rM   update_projectzProjectService.update_project   s    & '--44<<> $//J?',, 9 9=IIL+|<= ; ;=MNN #/G "-G FF7OIIKJJw#0O_f_i_ijj	G!,/ 	G"9-&?	<&X X %>|_%]]^ffho99,GH />>r:N(%NOO
 )) w99:BBD/3 	  Cc.B.BCKKM=E!#"9"9: ! ANN//4NL--/0-99"lK	)++-'	t '8(MM(&!9-'BYBYZ( " !088:		 5 5l CD	")))466\)&svv.C+4C(FF3K**1**,/FF)2G
 !''0FF7O3 !6 HHJ	L*-d=.A.I.I.K*L')8G&FF7OIIKJJw#**,

3 -#

3 $	J2DE2DQQYY[2DME#4#:#:#<V~~'G=,H#G, $= VO,
 6!**
 	
G  	G ; ;SXFF	G !Y 	G ; ;SXFF	G  ^*   O"8  		t@AKKM'A ( ( E EGrss		t2  		L:;KKM'A ( (%JKK		L F ! V$$%KWUV  	JHI	J  V  !C_UVst  C-Y!0R ;Y!> S SS #Y!;T<BY!3TY!T"5Y!AT ,T-CT B V #Y!%X )W+ X W08X :Y!>X; 	Y!	S
"#SS

Y!S 	T#S<<TY!	TY!TY!T 	V	(AVV		Y!	W(AW##W((Y!+X 0XX XX X84Y!7X88Y!;YY!YY!product_image_idc                   K   	 t        |       | j                  t        |      }|r|j                  rt        t        j                  d      t        j                  | |j                        }|st        dd      t        |t               d{   }t        |      }	 t!        t"        |j$                  t        |      t        t&                     d{   }t        |      }	t        |j*                        }
	 t        |	      |_        | j-                  |       | j/                          | j1                  |       	 t)        |
       t)        |       d	d
|j8                  |j:                  t        |	      dS # t        $ r(}t        t        j                  t        |            d}~ww xY w7 7 # t        $ r}t)        |       t        dd      |d}~ww xY w# t        $ r8}| j3                          t)        |	       t)        |       t        dd      |d}~ww xY w# t        $ r t4        j7                  d       Y w xY ww)z
        Regenerate one final image using a temporary overlay.
        Old image is replaced only if the whole process succeeds.
        NzImage record not foundrf   zAssociated template not foundrg   z Failed to regenerate final imagezFailed to update databasez Failed to delete old final imageTz$Final image regenerated successfully)rd   re   r   r*   new_final_image_path)r   r-   r   r   r.   r/   getr   r\   r4   r   	get_by_idr+   r   r1   r   r   r   r5   r6   r   r,   rk   rl   r>   rs   r7   r8   r9   r*   )rb   r   new_overlay_filerA   rB   img_rowtemplatetemp_overlay_pathnew_final_path_strnew_final_pathold_final_paths              rM   regenerate_single_imagez&ProjectService.regenerate_single_imageW  s!    	G!"23
 &&'78',, 9 9;STT -66r7;V;VW%DEE #<#
 

 !!23		R'8$""%&M"	( " 01 g667	K'*>':G$FF7OIIKJJw	A'
 	%& = '

!(!:!:$'$7
 	
{  	G ; ;SXFF	G
"  	R)*%GHcQ	R   	KKKM')*%@AsJ	K  	A?@	As   IE8 A?IF,I5F1 F/F1  I:AG =H 0I8	F)#F$$F))I/F1 1	G:GGI	H#3HHIH?<I>H??Ic                    t        j                  | |      }|st        t        j                  t
              t        j                  | |       t        j                  | |      }|D ]!  }	 t        t        |j                               # t        j                  | |       y # t        $ r# t        j                  d|j                         Y fw xY w)Nr"   z%Failed to delete final image file: %s)r   r[   r   r   r4   r   r=   r   rn   r   r   r,   r-   r7   r8   delete_by_project)r   rX   rD   r_   r`   s        rM   delete_projectzProjectService.delete_project  s    #//DF,E,Em\\ 	--gw?'77LC`D!5!567  	00*E  `  !H#J^J^_`s   *B!!)CCN)__name__
__module____qualname____doc__staticmethodr/   r	   r   r2   intr   rV   ra   r   r   r    rW   rM   r   r      s?   +^^^ ^ 
^ ^@ 
w 
c 
# 
xPS} 
_b 
kn 
 
 G   $ s
s
sms
 c]s
 s
 s
j Q
Q
Q
 Q
f F FS F FrW   r   N)0typingr   r   pathlibr   fastapir   r   fastapi.concurrencyr   sqlmodelr	   r
   app.core.loggingr   app.core.configr   app.core.constantsr   r   app.models.project_masterr   app.models.product_imager   app.repositories.project_repor   #app.repositories.product_image_repor   &app.repositories.product_template_repor   app.utils.imager   r   r   r   app.utils.generate_final_imager   r   r7   settingsOVERLAY_IMAGES_DIRECTORYr1   mkdirLOGO_IMAGES_DIRECTORYr0   FINAL_IMAGES_DIRECTORYr6   r   r   rW   rM   <module>r      s    !  ) 1 $ ) ( > 3 1 ; F L m m ?	h	>x889   dT  2H223   4$  /X445   D4  0\F \FrW   