
    y:iL                        d dl Z d dlZd dlmZmZ d dlmZmZ d dlmZ d dl	Z
d dlmZ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 d dlmZ d dlmZmZ d dlm Z m!Z!m"Z" d dl#m$Z$m%Z%m&Z& d dl'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZE d dlFmGZG d dlHmIZI d dlJmKZK d dlLmMZM d dlNmOZOmPZP dede"de!fdZQ e"       fdede"deRfdZS e"       fdede"deRfdZTdedeUdeRfdZVdeMdfdedeUdeeU   deeU   deeU   de!fd ZW e"       fded!ede"de!fd"ZXded#eOfd$ZYded%eUd&eUfd'ZZdedeUfd(Z[y))    N)datetimetimezone)CallableOptional)UUID)HTTPException
UploadFilestatus)FileResponse)Stringcast)IntegrityError)Session)StreamingResponse)Country)Region	SubRegion)DownloadFilesCreateSchemaDownloadFilesOutputSchemaExportDataFilterSchema)create_download_fileget_all_latest_download_filesget_all_latest_uploaded_files) generate_appellation_export_file generate_bottle_size_export_file(generate_colour_substitution_export_file!generate_global_noise_export_filegenerate_mongo_map_export_file%generate_producer_keyword_export_file#generate_producer_noise_export_file!generate_spread_table_export_filegenerate_varieties_export_filegenerate_wine_alias_export_filegenerate_wine_db_export_file!generate_wine_keyword_export_filegenerate_wine_noise_export_file%generate_word_elimination_export_file"generate_word_reserved_export_fileupdate_appellation_from_csvupdate_bottle_size_from_csv#update_colour_substitution_from_csvupdate_global_noise_from_csvupdate_mongo_map_from_csv update_producer_keyword_from_csvupdate_producer_noise_from_csvupdate_spread_table_from_csvupdate_varieties_from_csvupdate_wine_alias_from_csvupdate_wine_db_from_csvupdate_wine_keyword_from_csvupdate_wine_noise_from_csv update_word_elimination_from_csvupdate_word_reserved_from_csv)CreateFileWithPathSchema)create_file_from_path)APIException)EXPORT_DATA_SUB_FOLDER)ExportDataTypesExportDataTypesFileNamedbpayloadreturnc                 d  K   t        | |       d{   }d}|j                  2 3 d{   }||j                  d      z  }7 07 6 t        |j                     j
                   t        j                         j                  d       d}t        | |||j                         d{  7  }|S w)a  
    Generates and stores a download file based on the provided payload.
    :param db: Database session
    :param payload: ExportDataFilterSchema containing export type and other parameters
    :return: DownloadFilesOutputSchema containing details of the stored download file
    r>   r?   N utf-8%Y-%m-%d-%H%M%S.txt)r>   	file_namecontent	file_type)
get_export_filebody_iteratordecoder=   typevaluer   nowstrftimestore_files_locally)r>   r?   data_streamrH   chunkrG   download_files          c/var/www/html/wine-match-dev/backend/winematch-backend/src/apps/export_data/services/export_data.pygenerate_download_filerV   B   s      (2w??K G"00 ) )e5<<(( @)0 +7<<8>>?@W@WXi@j?kkopI-,,	  M s<   B0AB0AAAB0AA B0(B+)B0c                 v  K   |j                   xt        j                  k(  r t               }|ddS xt        j                  k(  r t               }|ddS xt        j                  k(  r t               }|ddS xt        j                  k(  r t               }|ddS xt        j                  k(  r t               }|ddS xt        j                  k(  r t               }|ddS xt        j                  k(  r t               }|ddS xt        j                   k(  r t#               }|ddS xt        j$                  k(  r t'               }|ddS xt        j(                  k(  r t+               }|ddS xt        j,                  k(  r t/               }|ddS xt        j0                  k(  r t3               }|ddS xt        j4                  k(  r t7               }|ddS xt        j8                  k(  r t;               }|ddS t        j<                  k(  rt?               }|ddS 	 tA        ddditB        jD                  d      w)z
    Fetches the export file based on the provided payload type.
    :param db: Database session
    :param payload: ExportDataFilterSchema containing export type and other parameters
    queuedtaskr
   rJ   	exceptionzInvalid export typeInvalid export type provided.moduleerrorstatus_codemessage)#rM   r<   WINE_DBr$   	MONGO_MAPr   WINE_KEYWORDr%   PRODUCER_KEYWORDr   GLOBAL_NOISEr   PRODUCER_NOISEr    
WINE_NOISEr&   SPREAD_TABLEr!   WORD_RESERVEDr(   BOTTLE_SIZEr   
WINE_ALIASr#   	VARIETIESr"   COLOUR_SUBSTITUTIONSr   WORD_ELIMINATIONr'   APPELLATIONr   r:   r
   HTTP_400_BAD_REQUEST)r>   r?   rZ   s      rU   rJ   rJ   _   s     ,,$_$$/1D H55&_&&13D H55)_))46D H55-_--8:D H55)_))46D H55+_++68D H55'_''24D H55)_))46D H55 +_**57D H55(_((35D H55'_''24D H55&_&&13D H551_11;=D H55-_--8:D H55((35D H55 ("$9:"777	 s   H7H9c                   K   t        |        d{   }|st        dddit        j                  d      |j	                  |j
                        s-t        ddd|j
                   d	it        j                  d
      |j	                  |j
                        }t        j                  j                  t        j                         t        d|j	                  d            }t        j                  j                  |      s"t        ddd| it        j                  d      t        ||j	                  d      d      S 7 .w)a=  
    Downloads a specific export file based on the provided type.
    Args:
        db (Session): Database session dependency.
        payload (ExportDataFilterSchema): Filter criteria for the export file, including type.
    Returns:
        StreamingResponse: Contains the export file data or an error message.
    r>   NrT   r[   No export files available.+No export files are available for download.r]   #No export file available for type: ..The requested export file type does not exist.
masterdatarG   File not found at path: 7The requested export file does not exist on the server.application/octet-streampathfilename
media_type)r   r:   r
   HTTP_404_NOT_FOUNDgetrM   osr~   joingetcwdr;   isfiler   )r>   r?   latest_files	files_objr~   s        rU   rT   rT      s%     7"==L" <=11A	
 	
 GLL)""Egll^ST UV11D	
 	
   .I77<<		%;\9==YdKefD77>>$"":4& AB11M	
 	
 {+- 9 >s   EE D.ErG   c                   K   	 t         j                  j                  t        j                         t        d      }t         j                  j                  ||      }t         j                  j                  |      s"t        ddd| it        j                  d      t        ||d      S # t        $ r-}t        ddt        |      it        j                  d	      d
}~ww xY ww)a#  
    Downloads a specific export file based on the provided file name.
    Args:
        db (Session): Database session dependency.
        file_name (str): The name of the file to be downloaded.
    Returns:
        StreamingResponse: Contains the export file data or an error message.
    ry   download_file_by_namer[   rz   z0The requested file does not exist on the server.r]   r|   r}   z&Failed to download the specified file.N)r   r~   r   r   r;   r   r:   r
   r   r   	ExceptionstrHTTP_500_INTERNAL_SERVER_ERROR)r>   rG   download_locationr~   es        rU   r   r      s     
GGLL6Ll[ww||-y9ww~~d#."&>tf$EF"55J	  1
 	

  
*A'==<	
 	

s)   C#B%B* )C#*	C 3(CC  C#rH   	subfolderrI   c                 R  K   t         j                  j                  t        j                         |      }t        j                  |d       t         j                  j                  ||      }|(t        |dd      5 }|j                  |       ddd       t         j                  j                  t        |      j                  dd      }t        | t        ||d	
             d{   }t        | t        |j                  |             d{   }	|	S # 1 sw Y   xY w7 <7 w)z
    Store the given content in a file under the specified subfolder in the current working directory.
    Stores the file in database and returns the DownloadFilesOutputSchema.
    Texist_okNwrD   encoding\/z
text/plain)	file_pathrG   mimerB   )file_idrI   )r   r~   r   r   makedirsopenwriter;   replacer9   r8   r   r   id)
r>   rG   rH   r   rI   r   r   fnew_filenew_download_files
             rU   rQ   rQ     s      RYY[)<KK!D1.	:I )S73 	qGGG	 3Y?GGcRI*(
 H 30PYZ  '	 	s=   A:D'<DAD'&D#')D'D%D'D D'%D'filec                 6  K   |j                          d{   }|j                  d      }t        |j                     j                   t        j                         j                  d       d}t        j                  j                  t        j                         t        d      }t        j                  |d       t        j                  j                  ||      }t        |dd	      5 }|j                  |       ddd       d
||dS 7 # 1 sw Y   xY ww)z
    Saves an uploaded export file based on the provided type.
    :param db: Database session
    :param payload: ExportDataFilterSchema containing export type and other parameters
    :return: DownloadFilesOutputSchema
    NrD   rE   rF   
uploaddataTr   r   r   success)r
   rG   r~   )readrL   r=   rM   rN   r   rO   rP   r   r~   r   r   r;   r   r   r   )	r>   r   r?   rH   file_contentrG   upload_location
local_pathr   s	            rU   save_uploaded_filer   -  s      IIKG>>'*L*7<<8>>?@W@WXi@j?kkopIggll299;0FUOKK$/oy9J	j#	0 A	  iLL   s(   DDCD+D=DDDrM   c                   K   t        |        d{   }|st        dddit        j                  d      |j	                  |      s#t        ddd| d	it        j                  d
      |j	                  |      }t
        j                  j                  t        j                         t        d|j	                  d            }t
        j                  j                  |      s"t        ddd| it        j                  d      |j	                  d      }|xt        j                  k(  r t        |      }|ddS xt        j                  k(  r t        |      }|ddS xt        j                   k(  r t#        |      }|ddS xt        j$                  k(  r t'        |      }|ddS xt        j(                  k(  r t+        |      }|ddS xt        j,                  k(  r t/        |      }|ddS xt        j0                  k(  r t3        |      }|ddS xt        j4                  k(  r t7        |      }|ddS xt        j8                  k(  r t;        |      }|ddS xt        j<                  k(  r t?        |      }|ddS xt        j@                  k(  r tC        |      }|ddS xt        jD                  k(  r tG        |      }|ddS xt        jH                  k(  r tK        |      }|ddS xt        jL                  k(  r tO        |      }|ddS t        jP                  k(  rtS        |      }|ddS 	 t        dddit        jT                  d      7 Nw)z
    Processes an uploaded export file based on the provided type.
    :param db: Database session
    :param payload: ExportDataFilterSchema containing export type and other parameters
    :return: Task status
    rs   NrT   r[   rt   ru   r]   rv   rw   rx   r   rG   rz   r{   )rG   rX   rY   process_uploaded_file_dater\   z+The provided export type is not recognized.)+r   r:   r
   r   r   r   r~   r   r   r;   r   r<   rb   r3   rc   r-   rd   r4   re   r.   rf   r,   rg   r/   rh   r5   ri   r0   rj   r7   rk   r*   rl   r2   rm   r1   rn   r+   ro   r6   rp   r)   rq   )r>   rM   r   r   r~   rG   rZ   s          rU   r   r   F  s     7"==L" <=11A	
 	
 D!""EdV1 MN11D	
 	
   &I77<<		%;\9==YdKefD77>>$"":4& AB11M	
 	
 k*I
$_$$*Y?D H55&_&&,yAD H55)_))/)DD H55-_--3iHD H55)_))/)DD H55+_++1IFD H55'_''-	BD H55)_))/)DD H55 +_**09ED H55(_((.CD H55'_''-	BD H55&_&&,yAD H551_116KD H55-_--3iHD H55((.CD H55 3"$CD"77E	 y >s   M#M MM#codedatec                 j  K   	 | d| d}t         j                  j                  t        j                         dd|      }t         j                  j	                  |      s"t        ddd| it        j                  d	      t        ||d
      S # t        $ r}dt        |      dcY d }~S d }~ww xY ww)N-z
-match.txtuploadsmatch_outputsrT   r[   rz   r{   r]   r|   r}   failedr
   r_   r   r~   r   r   r   r:   r
   r   r   r   r   )r>   r   r   rG   r~   r   s         rU   download_matched_filer     s     5fAdV:.	ww||BIIKOYOww~~d#&"&>tf$EF"55Q	  1
 	

  5"SV445s5   B3B
B B3	B0B+%B0&B3+B00B3c                 Z  K   	 t         j                  j                  t        j                         dd|      }t         j                  j	                  |      s"t        ddd| it        j                  d      t        ||d	      S # t        $ r}d
t        |      dcY d }~S d }~ww xY ww)Nr   historyrT   r[   rz   r{   r]   r|   r}   r   r   r   )r>   rG   r~   r   s       rU   download_history_filer     s     5ww||BIIKIyIww~~d#&"&>tf$EF"55Q	  1
 	

  5"SV445s5   B+BB B+	B(B#B(B+#B((B+)\ior   r   r   typingr   r   uuidr   pandaspdfastapir   r	   r
   fastapi.responsesr   
sqlalchemyr   r   sqlalchemy.excr   sqlalchemy.ormr   starlette.responsesr   src.apps.base.models.countryr   src.apps.base.models.regionsr   r   (src.apps.export_data.schemas.export_datar   r   r   +src.apps.export_data.services.download_filer   r   r   #src.apps.export_data.services.tasksr   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   src.apps.files.schemas.filer8   src.apps.files.services.filer9   src.core.exceptionsr:   src.utils.constantsr;   src.utils.enumsr<   r=   rV   anyrJ   rT   r   r   rQ   r   r   r   r        rU   <module>r      s   	 	 ' %   5 5 * # ) " 1 0 : 
 
       @ A > , 6 D# > '=&>NN#N 	Nf '=&>--#- 	-`#
#
#
 	#
R "5#$$$ c]$ }	$
 }$ $T '=&>MM
M $M 	M2kk
k\5G 53 5c 5,555r   