
    j)                        d Z ddlmZ ddlZddl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mZmZ ddlmZmZ dd	lmZmZ d
Zh dZddhZddhZdZdZddZddZddZ ddZ!ddZ"	 	 	 	 	 	 ddZ#y)z6Independent post-cleanup customer authority inventory.    )annotationsN)Path)Any)CustomerAdminError_require_customer_key_resolve_profile_root_resolve_registry_path)read_journalvalidate_fileverify_archive)AuthorityInventoryCleanupIntegrityError)shared_authority_countsverify_shared_projections)registry	bootstrap
onboardingoutboxkeyowner_actionservice_stateeventcustomer_data
activation
sent_event	candidate>   sendingprepared	deliveredaudit_pendingunknowndelivery_unknownzcustomer-activation-audit.jsonlzscheduled-deliveries.jsonlz customer-activation-journal.json)transaction_idcustomer_idregistry_path	data_rootchecklist_evidence_path
audit_pathregistry_sha256previous_registry_sha256audit_record_sha256
created_atprepared_atc                   t        |       }t        |       |j                         }	 t        j                  |      }t        fd|d   D              }|j                  d      }t        |t              r|j                  d      nd }|j                  d      du |du |fS # t        t        t        t        j                  f$ r}t        d       |d }~ww xY w)Nc              3  4   K   | ]  }|d    k(  s|  yw)customer_keyN ).0rowr   s     w/home/cube/projects/richard/.worktrees/nutricoach-v140-impl/dualcoach/profile/checkin_cli/customer_cleanup_inventory.py	<genexpr>z&read_registry_state.<locals>.<genexpr>;   s!     ['<N@SWZ@Z'<s   	customerszunknown customer: ai_processing_consentgrantedenabledF)r	   r   
read_bytesjsonloadsnextKeyError	TypeErrorStopIterationJSONDecodeErrorr   get
isinstancedict)	rootr   pathpayloaddocumentcustomerexcconsentr8   s	    `       r4   read_registry_staterL   5   s    !$'D$ooGF::g&[x'<[[ ll23G(27D(Agkk)$tG<<	"e+W-=wFF	 i0D0DE F #5cU!;<#EFs   ,B! !#CCCc                <   | j                  d      }| j                  d      }||fD cg c]  }t        |t              r|r| }}|rt        t	        |            dk7  rt        d      |||d   k7  rt        d      |||d   k7  rt        d      |d   S c c}w )Nr0   r$      z%authority customer binding is invalidr   z!authority customer_key is invalidz authority customer_id is invalid)rB   rC   strlensetr?   )r3   r0   r$   valuebindingss        r4   _customer_bindingrT   C   s    77>*L''-(K #K00EeS!e 	0  
 s3x=)Q.?@@LHQK$?;<<;(1+#=:;;A;s   Bc                    t         t              st        d      t         j	                  d            t
        us d   dvrt        d      t         fdt        D              rt        d      t         j	                  d      t              r d   st        d      t         j	                  d	      t              st        d
      t         j	                  d      t              st        d       j	                  d      }|t        |t              r|st        d       d   dk(  r/t         j	                  d      t              r d   st        d       d   dk(  r/t         j	                  d      t              r d   st        d       d   dv r*t         j	                  d      t              st        d       d   dk(  rt         fddD              rt        d      t                 S )Nz$activation journal must be an objectversion>   rN         z%activation journal version is invalidc              3  n   K   | ],  }t        j                  |      t               xs |     . y wNrC   rB   rO   r2   fieldr3   s     r4   r5   z/_validate_activation_journal.<locals>.<genexpr>Y   s4     
sNrUz#''%.#..@c%j.@Nr   25z,activation journal required field is invalidstatez#activation journal state is invalidrecovery_requiredz.activation journal recovery binding is invalidprevious_registryz/activation journal rollback registry is invalidprevious_audit_sha256z4activation journal previous audit binding is invalid	committedcommitted_atz,activation journal commit binding is invalid	abandonedabandoned_atz1activation journal abandonment binding is invalid>   rW   rX   nutrition_activation_receiptz/activation journal nutrition receipt is invalidrX   c              3  n   K   | ],  }t        j                  |      t               xs |     . y wrZ   r[   r\   s     r4   r5   z/_validate_activation_journal.<locals>.<genexpr>r   s=      #
E swwu~s++=3u:~=
r^   )staff_membership_evidence_path staff_membership_evidence_sha256staff_chat_inventory_sha256 membership_subscription_epoch_idz0activation journal membership binding is invalid)rC   rD   r?   typerB   intany$_ACTIVATION_JOURNAL_REQUIRED_STRINGSrO   boolrT   )r3   previous_audits   ` r4   _validate_activation_journalrs   T   s   c4 >??CGGIs*c)nI.M?@@

sNr
ssFGGcggg&,CL=>>cgg12D9HIIcgg12D9IJJWW45N!~s+>NOO
7|{"sww~.4C<OFGG
7|{"sww~.4C<OKLL
9~
./) IJJ
9~s #
#   JKKcJ    c                   | j                   t        k7  r | j                   t        vrt        d|        | j	                         sg S t        |        	 | j                  d      }| j                   t        k(  r1t        t        j                  |            }t        |      |k(  r|gS g S g }|j                         D ]R  }t        j                  |      }t        |t              st        d      t        |      |k(  sB|j                  |       T |S # t         t        t"        t        j$                  f$ r}t        d|        |d }~ww xY w)Nzunsupported authority file: utf-8encodingzauthority row must be an objectzauthority file is invalid: )name_ACTIVATION_JOURNAL_JSONL_AUTHORITIESr   existsr   	read_textrs   r;   r<   rT   
splitlinesrC   rD   r?   appendOSErrorUnicodeDecodeErrorrA   )rF   r   rG   r3   rowslinerR   rJ   s           r4   relevant_rowsr      s&   yy''DII=O,O#&B4&$IJJ;;=	$S..'.299++.tzz'/BCC-c2c9C5ArA%'&&(DJJt$EeT* ABB '3.E" ) Y 2D4H4HI S#&A$$HIsRSs,   AD &D (AD <D #E4EEc                6   	 t        |        t        j                  | j                  d            }t	        |t
              rt	        |j                  d      t              st        |S # t        t        t        j                  f$ r}t        d      |d }~ww xY w)Nrv   rw   	inventoryzcleanup manifest is invalid)r   r;   r<   r}   rC   rD   rB   listr?   r   rA   r   )rF   rR   rJ   s      r4   _load_inventory_manifestr      s}    Ld

4>>7>;<%&j;9OQU.VOY 4 45 L#$ABKLs   A&A) )BBBc                  !" t        t        |             }t        |      }t        ||      \  }}}t        j                  t        d      }d}|r|sdx|d<   }|dz  |z  }	|	j                         rt        |	j                  d            ng }
|
D ]w  }|j                         s|j                  |	      j                         j                         j                  dd      !t        !fdd	D        d
      }||xx   dz  cc<   |dz  }y t!        ||      \  }}}}||z  }|dxx   ||z   z  cc<   |dz  }t#        ||      D ]X  }t%        |j'                  d|j'                  dd                  }|t(        v r|dz  }<|t*        v s|s|dz  }L|dxx   dz  cc<   Z |dz  |dz  f}|D ]`  }t#        ||      D ]O  }|dxx   dz  cc<   |j,                  t.        k(  s$|j'                  d      dvs|j'                  d      dusK|dz  }Q b |dz  }|h|}|dz  j                  d      D ]  }|j                         r||v s||j0                  v r&|	|j0                  v r5|j                  |      j                         j                         j                  dd      "|"vrwt        "fdd	D        d      }||xx   dz  cc<   |dz  } || dz  }t3        |      }t5        |xr |d   j'                  d      dk(        }d}|rt%        |d   d         }|d z  |z  }	 |d!z  }t7        |      }t9        j:                  |j=                               j?                         }||d   j'                  d"      k7  rtA        d#      tC        ||d$          tE        ||||j'                  d%g              d&}|r|nd} tG        jH                  |||||||| ||'
      S # t@        $ r Y 0w xY w)(zEIndependently enumerate every supported customer authority namespace.r   rN   r   zdata/customers*-_c              3  *   K   | ]
  }|v r|  y wrZ   r1   )r2   ry   labels     r4   r5   z3post_cleanup_authority_inventory.<locals>.<genexpr>   s&        d      )r   r   r   r   r   r   r   r   r   zdata/scheduled-deliveries.jsonlr_   status r   z%data/customer-activation-journal.jsonz$data/customer-activation-audit.jsonlr   >   re   rc   r`   Fzdata/customer-cleanupdatac              3  *   K   | ]
  }|v r|  y wrZ   r1   )r2   ry   relatives     r4   r5   z3post_cleanup_authority_inventory.<locals>.<genexpr>   s'      # d !  r   r   z.journal.jsonlphaserc   operation_idarchiveszmanifest.jsonmanifest_sha256z cleanup manifest digest mismatchr   shared_ledger_projectionsT)
r0   disablednonconsenting
categoriesactive_countpending_countunknown_countorphan_countarchive_verifiedjournal_committed)%r   r   r   rL   rD   fromkeys_CATEGORIESr|   r   rglobis_filerelative_toas_posixlowerreplacer=   r   r   rO   rB   _PENDING_STATES_UNKNOWN_STATESry   rz   parentsr
   rq   r   hashlibsha256r:   	hexdigestr   r   r   r   build)#profile_rootr0   rE   r   r   r   r   r   activecustomer_rootcustomer_filesrF   categoryshared_activependingr!   terminal_owner_actionsschedule_pathr3   r_   activation_pathscleanupexcludedjournaljournal_rowsrc   verified	operationarchivemanifest_pathmanifestmanifest_digestorphanr   r   s#                                    @@r4    post_cleanup_authority_inventoryr      s\    !l!34D

-C!4T3!?HmQ{A.JF=*++
:++c1M7D7K7K7MT---c23SUN||~  /88:@@BJJ3PST     
 	8!!  ?VVZ\_>`;M7G%;
mF~-2H"HH<<M]C0CGGGSWWXr%:;<O#qLGo%UqLG|$)$ 1 	6655 ! s+C|$)$yy// (BB77./u<1 , ! ,,G1 01H%%c*||~!1W5LDLL(##D)224::<DDS#Nh#  # 
 	8!!! +" 3%~..G(L\Rl2&6&:&:7&C{&RSIHQ78	J&2	#o5M/>H%nn]-E-E-GHRRTO,q/"5"56G"HH+,NOO7H[$9:%8"=	 H !VaF###!#  % 		s   BO 	O O )rE   r   r   rO   returnztuple[bool, bool, bytes])r3   dict[str, Any]r   rO   )r3   objectr   r   )rF   r   r   rO   r   zlist[dict[str, Any]])rF   r   r   r   )r   z
Path | strr0   rO   r   r   )$__doc__
__future__r   r   r;   pathlibr   typingr   checkin_cli.customer_adminr   r   r   r	   checkin_cli.customer_cleanup_fsr
   r   r   #checkin_cli.customer_cleanup_modelsr   r   #checkin_cli.customer_cleanup_sharedr   r   r   r   r   r{   rz   rp   rL   rT   rs   r   r   r   r1   rt   r4   <module>r      s    < "      X W

 H01%   9 ( $G")XS.Lhh,/hhrt   