
    j}                       d Z ddlmZ ddlZ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mZ ddlmZmZ dd	lmZmZmZmZ d
dlmZmZ  G d de      Z G d de      Z edd       G d d             Z edd       G d d             Z edd       G d d             Z 	 	 	 	 	 	 	 	 	 	 dAdZ! G d d      Z"dZ# e$       Z%dZ&dBdZ'dCdZ( edd       G d  d!             Z)	 	 	 	 	 	 	 	 	 	 	 	 	 	 dDd"Z*ee+ ed
d#$      f   Z, G d% d&e      Z- G d' d(e      Z. G d) d*e      Z/ G d+ d,e      Z0 G d- d.e      Z1 G d/ d0e      Z2 G d1 d2e      Z3 G d3 d4e      Z4 G d5 d6e      Z5 edd       G d7 d             Z6 edd       G d8 d9             Z7dEd:Z8dd;	 	 	 	 	 	 	 dFd<Z9	 	 	 	 	 	 	 	 dGd=Z:dHd>Z;	 	 	 	 	 	 	 	 	 	 dId?Z<dJd@Z=y)KzDValidated customer registry and twelve-week nutrition plan boundary.    )annotationsN)	dataclassfield)datetime)Path)Mapping)	AnnotatedLiteral)	BaseModel
ConfigDictFieldmodel_validator   )CustomerTrainingScheduleEntryTrainerAssignmentc                      e Zd Zy)CustomerRegistryErrorN)__name__
__module____qualname__     /home/cube/projects/richard/traning coach/task-12-independent-verification-r9/build/hermes-full/dualcoach/profile/checkin_cli/customer_coaching.pyr   r      s    r   r   c                      e Zd ZdZy)DualCoachCoordinatorErrorzBRaised when a registered-customer dual-coach transition is unsafe.N)r   r   r   __doc__r   r   r   r   r      s    Lr   r   T)frozenslotsc                  &    e Zd ZU dZded<   ded<   y)ScheduleConfirmRequestz9Typed gateway input for one pinned schedule confirmation.strcustomer_keyobjecteventN)r   r   r   r   __annotations__r   r   r   r!   r!      s    CMr   r!   c                  ,    e Zd ZU ded<   ded<   ded<   y)ScheduleConfirmReceiptMapping[str, object]canonical_eventcanonical_sequenceadaptive_projectionNr   r   r   r&   r   r   r   r(   r(   !   s    )),,--r   r(   c                  ^    e Zd ZU dZded<   ded<   ded<   ded<   ded<   ded	<   dd
ZddZy)CustomerDailyProjectionzANarrow, customer-safe daily source; it has no delivery authority.r"   today_stateprior_comparison	judgementreasonztuple[str, ...]actions
next_checkc                L   | j                   r$| j                  r| j                  r| j                  st	        d      dt        | j                        cxk  rdk  r)n t	        d      t        d | j                  D              rt	        d      | j                  st	        d      y )Nz'daily customer projection is incompleter      c              3  >   K   | ]  }|j                            y wN)strip.0items     r   	<genexpr>z8CustomerDailyProjection.__post_init__.<locals>.<genexpr>5   s     1\|tdjjl2B|s   z"daily customer actions are invalidz%daily customer next check is required)	r0   r1   r2   r3   
ValueErrorlenr4   anyr5   selfs    r   __post_init__z%CustomerDailyProjection.__post_init__2   s    t'<'<DNNZ^ZeZeFGGC%**ABB /21\t||1\.\ABBDEE r   c           
         dj                  d| j                   d| j                   d| j                   d| j                   ddj                  | j
                        z   d| j                   f      S )	N
u   오늘 상태: u   이전 흐름과 비교: u   오늘 판단: u   판단 이유: u   오늘 할 일: z / u   다음 확인: )joinr0   r1   r2   r3   r4   r5   rB   s    r   renderzCustomerDailyProjection.render:   s{    yyd../0'(=(='>?dnn-.dkk]+DLL!99doo./
  	r   NreturnNonerJ   r"   )r   r   r   r   r&   rD   rH   r   r   r   r/   r/   '   s1    KNKOFr   r/   CustomerRuntimec          
     ~   ddl mm}m}m} t        | t              rt        | j                  t              st        d      t        |      r#j                  | j                  j                  k7  rt        d      |rt        |      dkD  rt        d      t        |      }t        fd|D              rt        d      t        fd	|D              rt        d
      t        |t              r|j!                         rt        |      dkD  rt        d      j"                  }|j$                  rdnd}	|j&                  d}
nd|j&                   d}
j(                  |j*                  u rdnd}j(                  |j*                  u rdn |j,                        }t/        |	|
||t        d |D              |      S )zEBuild the gateway's read-only daily source from an approved proposal.r   )CustomerActionContinuityDecisionNutritionProposalvalidate_explanationz8daily customer projection requires a registered customerz+daily customer projection customer mismatchr7   z6daily customer actions must contain one to three itemsc              3  8   K   | ]  }t        |         y wr9   )
isinstance)r<   r=   rO   s     r   r>   z=build_registered_daily_customer_projection.<locals>.<genexpr>[   s     
Ohdz$ 899hs   z:daily customer actions require approved continuity recordsc              3     K   | ]S  }|j                   j                   k7  xs4 |j                  j                  k7  xs |j                  j                  k7   U y wr9   )r#   approved_proposal_digestdigestrevision)r<   r=   proposals     r   r>   z=build_registered_daily_customer_projection.<locals>.<genexpr>]   sa       D 	X222 	.((HOO;	.==H---	. s   AAz9daily customer actions do not match the approved proposal   z$daily customer next check is invaliduB   최근 기록을 바탕으로 오늘 계획을 확인했습니다.uN   오늘 기록을 받으면 계획을 더 정확히 확인할 수 있습니다.uF   이전 흐름과 비교할 기록이 아직 충분하지 않습니다.u   최근 변화 흐름은 주간 u   %입니다.u+   오늘은 현재 계획을 유지합니다.uO   오늘 계획을 확인하고 필요한 조정을 운영자가 검토합니다.u^   최근 흐름이 현재 계획을 바꿀 근거를 만들지 않아 유지가 적절합니다.c              3  4   K   | ]  }|j                     y wr9   )action_textr;   s     r   r>   z=build_registered_daily_customer_projection.<locals>.<genexpr>{   s     484d8   )checkin_cli.adaptive_nutritionrO   rP   rQ   rR   rT   rM   bindingRegisteredCustomerBindingr   r#   specr@   tuplerA   r"   r:   snapshotcurrent_samplesweekly_rate_percentdecisionMAINTAINexplanationr/   )runtimerY   r4   r5   rP   rQ   rR   selectedrc   r0   
comparisonr2   r3   rO   s    `           @r   *build_registered_daily_customer_projectionrl   E   s     g/z'//Sl7m#$^__h 12h6K6Kw||OhOh6h#$QRRc'lQ&#$\]]W~H

Oh
OO#$`aa
  	  $$_``j#&j.>.>.@C
OVYDY#$JKK  H ## 	M)y  ##+]
6x7S7S6TT_`
  1 11 	6^   1 11 	i!("6"6A 
 #ZF4844j r   c                     e Zd ZdZddZddZddZedd       ZddZ	ddZ
ddZdd	Zd d
Zedd       Zd!dZddZd"dZd#dZd$dZd%dZeZddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d&dZ	 	 	 	 	 	 d'dZd(dZed)d       Zy)*&RegisteredCustomerDualCoachCoordinatora  The only registered-customer authority for dual-coach confirmation.

    Canonical authority is committed first under its lock.  The projection is a
    separately durable, idempotent reconciliation step: disagreement raises and
    never causes a second canonical mutation.
    c                j   t        |t              st        d      t        |j                  t              st        d      || _        ddlm} | j                         | _
         ||j                  dz  | j                  |j                        | _        | j                          | j                          y )Nz/dual-coach coordinator requires CustomerRuntimez1registered customer runtime has no sealed bindingr   )AdaptiveEventStorezevents.jsonl)canonical_transactionroot)rT   rM   	TypeErrorr_   r`   r   ri   r^   rp   _canonical_transactionrq   nutrition_plans_rootadaptive_storereconcile_schedule_referencereconcile_pending)rC   ri   rp   s      r   __init__z/RegisteredCustomerDualCoachCoordinator.__init__   s    '?3MNN'//+DE+,_``E%)%@%@%B"0((>9"&"<"<--

 	))+ r   c                D    ddl m} |j                  | j                        S )Nr   )CanonicalEventTransaction)checkin_cli.storer{   for_customer_runtimeri   )rC   r{   s     r   rt   z=RegisteredCustomerDualCoachCoordinator._canonical_transaction   s    ?(==dllKKr   c                Z    | j                  |       | j                  j                  |      S r9   )_require_customerrq   current_schedule_referencerC   r#   s     r   current_referencez8RegisteredCustomerDualCoachCoordinator.current_reference   s'    |,))DD\RRr   c                4    | j                   j                  dz  S )Nzschedule-reference-pending.jsonri   ru   rB   s    r   _reference_pending_pathz>RegisteredCustomerDualCoachCoordinator._reference_pending_path   s    ||003TTTr   c                *   ddl m}m}  || j                        }| j                  j                  dz  }	 t        j                  |j                  d            }|d   }|d   }d	D 	ci c]  }	|	|j                  |	       }
}	t        |      t        us!|dk  st!        |t"              r| |||
      k7  rt        d
      ||| j                  j$                  j&                  fS # t        t        t        t        f$ r}t        d      |d }~ww xY wc c}	w )Nr   )feature_config_digest$load_verified_dual_coach_risk_policyfeature-epoch.jsonutf-8encodingepochconfig_digestz%adaptive feature epoch is unavailableanalytics_shadowoperator_candidates
activationdeliveryz!adaptive feature epoch is invalid)r^   r   r   ri   ru   jsonloads	read_textKeyErrorOSErrorrs   r?   r   gettypeintrT   r"   registered_bindingbinding_digest)rC   r   r   policyfeature_pathdocumentr   r   excnameflagss              r   _strategy_pinsz5RegisteredCustomerDualCoachCoordinator._strategy_pins   s   	

 6dllC||88;OO	^zz,"8"8'"8"JKHW%E$_5M
 ^
] (,,t$$] 	 

 Ks"qymS1 5eU CC+,OPPudll==LLLL '9j9 	^+,STZ]]	^
s   /C# (D#D<DDc                    ddl m}m}  j                  j                  dz  }	 t        j                  |j                  d            }|d   }|d   }dD ci c]  }||j                  |       }}t        |      t        us!|dk  st        |t              r| |||      k7  rt        d	      	 t#         fd
t%         j&                  j)                               D        d      }	|	- | j                  j*                  j,                  dd      }
|
|fS  ||	j                  d      |	d   d      }
|
|fS c c}w # t        t        t         t        f$ r d}Y w xY w)zHPin held reviews to live strategy and epoch without reading risk policy.r   )r   rW   r   r   r   r   r   r   zfeature epoch is invalidc              3     K   | ]m  }|j                  d       dv rXt        |j                  d      t              r9|d   j                  d      j                  j                  j
                  k(  r| o yw)
event_type>   schedule_strategy_baselineschedule_strategy_confirmedpayloadr#   N)r   rT   r	   ri   ra   r#   )r<   rowrC   s     r   r>   zSRegisteredCustomerDualCoachCoordinator._unavailable_risk_context.<locals>.<genexpr>   sh      ?C77<(PQswwy17;	N&&~6$,,:K:K:X:XX ?s   A3A6Nunprojected)r   strategy_stateevent_idr   )strategy_event_idstrategy_payload)r^   r   rW   ri   ru   r   r   r   r   r   r   rT   r"   r?   r   r   rs   nextreversedrv   readr   r   )rC   r   rW   r   r   r   r   r   r   strategysource_strategy_digests   `          r   _unavailable_risk_contextz@RegisteredCustomerDualCoachCoordinator._unavailable_risk_context   s   P||88;OO	zz,"8"8'"8"JKHW%E$_5M baD hll4((a  
 U3&19!-5 $9%$GG !;<< H
 #D$7$7$<$<$>? 

 %+&*ll&E&E&T&T"/- &" &u,,	 &,%-\\*%=$,Y$7- &" &u,,E '9j9 	E	s#   3D; D60?D; 6D; ;EEc           	     @   ddl m}m} | j                  |       t	        ||      r0|j
                  |j                  |j                  hvs|j                  t        d      | j                         \  }}}||j                  dd      | j                  |      |j                  |j                  |j                  ||d}| j                   }	|	j"                  j%                  ddd	
       |	j'                  d|	j(                   dt+        j,                          d      }
	 |
j/                  dd      5 }|j1                  t3        j4                  |ddd             |j7                          t+        j8                  |j;                                ddd       |
j=                  d       t+        j>                  |
|	       |	j=                  d       |
jA                         r|
jC                          yy# 1 sw Y   cxY w# |
jA                         r|
jC                          w w xY w)zDDurably reserve baseline reconciliation before the canonical append.r   Event	EventTypeNz/dual-coach schedule reference event is requiredr   Tmodeexclude_none)r#   r%   event_digestpolicy_versionpolicy_digestpolicy_document_digestr   parent_digest  parentsexist_okr   ..tmpxr   r   F,:ensure_ascii	sort_keys
separators  )"checkin_cli.modelsr   r   r   rT   r   SCHEDULE_REFERENCESCHEDULE_CORRECTIONschedule_referencer   r   
model_dump_event_digestversionr   document_digestr   parentmkdir	with_namer   osgetpidopenwriter   dumpsflushfsyncfilenochmodreplaceexistsunlink)rC   r%   r#   r   r   r   r   r   r   path	temporaryhandles               r   stage_schedule_referencez?RegisteredCustomerDualCoachCoordinator.stage_schedule_reference   s   7|,5%(	(D(DiFcFc'dd''/+,]^^'+':':'<$}(%%6%E ..u5$nn#11&,&<&<*	
 ++$EBNNQtyyk299;-t#DE	
	#g6&TZZet`jkl) 7 OOE"JJy$'JJu!  " " 76 !  " "s&   G: 0AG.A G: .G73G: :#Hc                N   | j                   }|j                         sy 	 t        j                  |j	                  d            }|j                  di       j                  d      |k7  rt        d      |j                          y # t
        t        f$ r}t        d      |d }~ww xY w)Nr   r   ,schedule reference recovery state is invalidr%   r   z,another schedule reference requires recovery)
r   r   r   r   r   r   r?   r   r   r   )rC   r   r   pendingr   s        r   !abandon_staged_schedule_referencezHRegisteredCustomerDualCoachCoordinator.abandon_staged_schedule_reference  s    ++{{}	ejj!ABG ;;w#''
3x?+,Z[[	 $ 	e+,Z[add	e   %B B$BB$c           
        | j                   }|j                         sy	 t        j                  |j	                  d            }ddlm} |j                  |d         |d   }|| j                  j                  j                  k7  s#|j!                  d	      | j#                        k7  rt        d
      | j$                  j'                         }t)        fd|j*                  D        d      }|y|j-                  dd      j-                  dd      k7  rt        d      | j/                         \  }}	}
|j!                  d      |j0                  k7  sd|j!                  d      |j2                  k7  sF|j!                  d      |j4                  k7  s(|j!                  d      |	k7  s|j!                  d      |
k7  rt        d      | j$                  j7                  |      }| j8                  j;                  ||j<                  ||j0                  |j2                  |j4                  |	|
      }|j?                          |S # t        t        t        t        f$ r}t        d      |d}~ww xY w)zGAppend the restrictive baseline once after its canonical source exists.Nr   r   r   r   r%   r#   r   r   z?schedule reference recovery state mismatches customer authorityc              3  V   K   | ]   }|j                   j                   k(  s| " y wr9   r   r<   r=   r%   s     r   r>   zVRegisteredCustomerDualCoachCoordinator.reconcile_schedule_reference.<locals>.<genexpr>)  !     ^?4dmmu~~>]$?   ))r   Tr   z:schedule reference recovery conflicts with canonical eventr   r   r   r   r   z3schedule reference recovery pins mismatch authority)r#   source_reference_idsource_reference_digestr   r   r   r   r   ) r   r   r   r   r   r   r   model_validater   r   rs   r?   r   ri   ra   r#   r   r   rq   read_snapshotr   eventsr   r   r   r   r   schedule_reference_digestrv   project_schedule_baseliner   r   )rC   r   r   r   r#   r   rc   	canonicalr   r   r   reference_digestbaseliner%   s                @r   rw   zCRegisteredCustomerDualCoachCoordinator.reconcile_schedule_reference  s9   ++{{}	ejj!ABG0(()9:E">2L 4<<,,999W[[=X\`\n\not\u=u+,mnn--;;=^8??^`de	  f4 @V$?@ ,L  (,':':'<$}KK()V^^;{{?+v/C/CC{{348N8NN{{7#u,{{?+}<+,abb55OOPYZ&&@@% ) 2 2$4!>> ..#)#9#9' A 	
 	I '9j9 	e+,Z[add	es   AH< <I&I!!I&c                4    | j                   j                  dz  S )Nz"schedule-confirmation-pending.jsonr   rB   s    r   _pending_pathz4RegisteredCustomerDualCoachCoordinator._pending_pathJ  s    ||003WWWr   c           	        ddl m} t        ||      st        d      ||j	                  dd      | j                  |      |j                  |j                  |j                  d}| j                  }|j                  j                  ddd	       |j                  d
|j                   d
t        j                          d      }	 |j!                  dd      5 }|j#                  t%        j&                  |ddd             |j)                          t        j*                  |j-                                d d d        |j/                  d       t        j0                  ||       |j/                  d       |j3                         r|j5                          y y # 1 sw Y   cxY w# |j3                         r|j5                          w w xY w)Nr   r   z(pending confirmation event must be typedr   Tr   )r#   r%   r   r   r   r   r   r   r   r   r   r   r   Fr   r   r   )r   r   rT   rs   r   r   r   r   r   r  r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )	rC   r%   r#   r   r   r   r   r   r   s	            r   _write_pendingz5RegisteredCustomerDualCoachCoordinator._write_pendingN  sm   ,%'FGG(%%6%E ..u5$nn#11&,&<&<
 !!$EBNNQtyyk299;-t#DE	
	#g6&TZZet`jkl) 7 OOE"JJy$'JJu!  " " 76 !  " "s&   F! AF3A F! FF! !#Gc                N   | j                   }|j                         sy 	 t        j                  |j	                  d            }|j                  di       j                  d      |k7  rt        d      |j                          y # t
        t        f$ r}t        d      |d }~ww xY w)Nr   r   /schedule confirmation recovery state is invalidr%   r   z/another schedule confirmation requires recovery)
r  r   r   r   r   r   r?   r   r   r   )rC   r   r   r   r   s        r   _clear_pendingz5RegisteredCustomerDualCoachCoordinator._clear_pendingj  s    !!{{}	hjj!ABG ;;w#''
3x?+,]^^	 $ 	h+,]^dgg	hr   c                l   | j                   }|j                         sy	 t        j                  |j	                  d            }|d   }ddlm} |j                  |d         || j                  j                  j                  k7  s#|j!                  d	      | j#                        k7  rt        d
      | j$                  j'                         }t)        fd|j*                  D        d      }|y|j-                  d      j-                  d      k7  rt        d      ddlm}  || j                        }	|j!                  d      |	j2                  k7  s<|j!                  d      |	j4                  k7  s|j!                  d      |	j6                  k7  rt        d      | j9                  ||	      }
t)        fd|j:                  D              }| j=                  j>                         tA        |j-                  dd      ||
      S # t        t        t        t        f$ r}t        d      |d}~ww xY w)zGFinish the sole durable post-canonical projection, or stop on mismatch.Nr   r   r#   r   r   r%   r  r   zBschedule confirmation recovery state mismatches customer authorityc              3  V   K   | ]   }|j                   j                   k(  s| " y wr9   r   r   s     r   r>   zKRegisteredCustomerDualCoachCoordinator.reconcile_pending.<locals>.<genexpr>  r   r   T)r   z0canonical confirmation mismatches recovery stater   r   r   r   z:schedule confirmation recovery policy mismatches authorityc              3  H   K   | ]  }|d    j                   k(  s|  yw)r   Nr   )r<   r   r%   s     r   r>   zKRegisteredCustomerDualCoachCoordinator.reconcile_pending.<locals>.<genexpr>  s&     c'=ZTYTbTbAb'=s   ""r   r   r*   r+   r,   )!r  r   r   r   r   r   r   r   r   r   r?   rs   r   ri   ra   r#   r   r   rq   r   r   r   r   r^   r   r   r   r   _project_confirmationsequence_rowsr	  r   r(   )rC   r   r   r#   r   r   rc   r   r   r   
projectionsequencer%   s               @r   rx   z8RegisteredCustomerDualCoachCoordinator.reconcile_pendingv  s   !!{{}	hjj!ABG">2L0(()9:E 4<<,,999W[[=X\`\n\not\u=u+,pqq--;;=^8??^`de	T2e6F6FTX6F6YY+,^__W5dllCKK()V^^;{{?+v/C/CC{{348N8NN+,hii//|VL
cx'='=ccENN+%%00f40P' *
 	
+ ':y9 	h+,]^dgg	hs   AH	 	H3"H..H3c                   ddl m} t        ||      st        d      |j                  }|t        d      | j                  |      }||j                  |j                  k7  rt        d      | j                  j                  |      }||j                  k7  rt        d      | j                         \  }}	}
|j                  |j                  k7  s2|j                  |j                  k7  s|j                  |j                  k7  rt        d      | j                   j#                         D cg c]D  }|d   d	k(  r:|d
   j%                  d      |j                  k(  r|d
   j%                  d      |k(  r|F }}t'        |      dk7  rt        d      ddlm}  || j,                  j.                  j0                  d   |      }|j2                  j4                  |j6                  D ch c]  }|j8                  dk7  r|j:                   c}t=        fdt?        d      D              }| j                   jA                  |j                  |d|j                  |	|      }| j                   jC                  ||j                  ||j                  |d   |j                  |j                  |j                  |	|d   d   ||j2                  jD                        S c c}w c c}w )Nr   r   +dual-coach confirmation event must be typedz*dual-coach confirmation payload is missing0dual-coach confirmation reference is not currentz3dual-coach confirmation reference digest is invalidz3dual-coach confirmation policy mismatches authorityr   r   r   r   r   r   z/dual-coach confirmation baseline is unavailable)*load_approved_adaptive_registration_inputs   restc              3  n   K   | ],  }j                  j                         |z         v rd nd . yw)trainingr  N)fromordinal	toordinal)r<   offsetstarttraining_dayss     r   r>   zORegisteredCustomerDualCoachCoordinator._project_confirmation.<locals>.<genexpr>  s=      
"  ++EOO,=,FG=XJ^dd"s   25   schedule_confirmation)root_event_idr#   mapped_flowobservation_kst_day
session_idwriter_epochroot_preimage_digest
row_digestr   )r#   r   r   confirmation_idsource_day_mapping_digestr   r   r   r   r   
categorieslast_change_note)#r   r   rT   rs   r!  r   r   r   reference_event_idrq   r   r  r   r   r   r   rv   r   r   r@   checkin_cli.customer_adminr  ri   customer_rootr   r   session_kst_datetraining_scheduleload_categoryr   rb   rangeappend_source_day_mapping#project_confirmed_schedule_strategyr,  )rC   r%   r#   r   r   r   	referencer  pinned_policyr   _r   baseline_rowsr  registrationr=   r+  mappingr  r  s                     @@r   r  z<RegisteredCustomerDualCoachCoordinator._project_confirmation  s   ,%'IJJ--?+,XYY**<8		 2 2g6P6P P+,^__55OOPYZw777+,abb"&"5"5"7ua!!V^^3**f.B.BB,,0F0FF+,abb..335
5C< $@@I""#89Y=O=OOI""#<=AQQ 5 	 
 }"+,]^^YALL&&..q1<
 ,,=="."@"@
"@$!!V+ II"@
  
(
 

 %%??#,,%/ %~~!1 @ 
 ""FF% ) 2 2$4!NN&-l&;!>> ..#)#9#9'*:6!&99JJ G 
 	
?

s   +A	K#"Kc                f   ddl m} ddlm}m}m}m} ddlm} ddl	m
}	 t        ||      st        d      | j                  j                         }
 |	|
j                  |      }|t        d      | j                   j"                  j$                  }| j'                  |      }	  || j                         }	  | |tM        |d                |tM        |d               tM        |d         tM        |d         tM        |d         tM        |d               } |||      }||j0                  ||j5                         tM        |jR                        tM        |jT                        |jV                  |jX                  |jZ                  |j\                  d|j8                  |j:                  |j<                  |j^                  ta        |jb                        |jd                  d}| jF                  jI                  d
|d|j0                         S # t(        t*        t,        f$ r | j/                         \  }} ||||j0                  |||      }|j$                  |j2                  j5                         |j6                  |j8                  |j:                  |j<                  |j>                  |j@                  |jB                  |jD                  d	
}| jF                  jI                  d
i ||d|j6                  gdd|jJ                        cY S w xY w# tN        tP        t,        f$ r}t        d      |d}~ww xY w)z@Verify policy custody before evaluating the six terminal inputs.r   )Decimal)DualCoachRiskEvidence_evaluate_dual_coach_riskheld_dual_coach_risk_candidater   r   )terminal_morning_root_kst_dayz"terminal morning event is requiredN)r#   evaluation_kst_dayterminal_checkin_idterminal_checkin_digestr   r   )
r#   rB  reason_coder   r   r   rC  rD  r   r   dual_coach_risk_reviewT)candidate_preimagescorereasonsheld
dedupe_keyweight_change_percentsleep_durationfatiguepainexercise_feasibilitymeal_deviation)rM  sleep_hoursrO  rP  rQ  rR  z)terminal morning risk evidence is invalid)r#   rC  rD  rB  evidencer   r   r   rH  rI  rJ  zdual-coach-risk:)3decimalr=  r^   r>  r?  r@  r   r   r   r|   rA  rT   r   rq   r   r   ri   ra   r#   r   r   rs   r?   r   r   rB  	isoformatrE  r   r   r   rC  rD  r   r   rv   appendrL  r"   ArithmeticErrorr   rM  rS  rO  rP  rQ  rR  rH  listrI  rJ  )rC   r%   answersr=  r>  r?  r@  r   r   rA  rc   rB  r#   rD  r   r   r   	candidatepreimagerT  
evaluationr   r   s                          r   record_terminal_morning_riskzCRegisteredCustomerDualCoachCoordinator.record_terminal_morning_risk  s!   #	
 	
 	-C%'+,PQQ--;;=:8??ER%+,PQQ||((55"&"4"4U";"	9$,,GFF	b,&-c':Q2R.S&T#C0@(A$BCGI./)%(1G)H%I"7+;#<=H 368DJ )#(>>'>"4">">"@),X-K-K)L"8#7#78#++ (0(E(E"*"9"9 )77'55&0&G&G%%J../OO%
( ""))$g<LU^^L\:] * 
 	
E J/  	,0,J,J,L)"E6)#5$)NN(?'=I !* 6 6&/&B&B&L&L&N(44"+":":!*!8!8*3*J*J'0'D'D+4+L+L*3*J*J"H &&--(*2! ) 5 56  %// . 
 
- 	X  :6 	b+,WX^aa	bs,   "H 5A+L C:LLL0L++L0c                   t        |t              st        d      | j                  |j                         ddlm}m} ddlm	} t        |j                  |      st        d      |j                  }|j                  |j                  urt        d       || j                        }|j                  }| j!                  |j                        }|C|A|j"                  |j$                  k7  s(| j&                  j)                  |      |j*                  k7  rt        d      | j-                  ||j                         | j/                          | j1                  ||j                  |       	 | j&                  j3                  ||j                        }	| j5                  ||j                  |      }
| j9                  |j"                         t;        |	d
   |	d   |
      S # t6        $ r}t        d	      |d }~ww xY w)Nz7dual-coach confirmation requires ScheduleConfirmRequestr   r   r  r  z)dual-coach confirmation event is requiredr  r#   z7canonical confirmation requires adaptive reconciliationr*   r  r  )rT   r!   rs   r   r#   r   r   r   r^   r   r%   r   SCHEDULE_CONFIRMATIONr   ri   r!  r   r   r-  rq   r   r  r   rw   r  append_schedule_confirmationr  r?   r	  r(   )rC   requestr   r   r   r%   r   r   r6  r   r  r   s               r   confirmz.RegisteredCustomerDualCoachCoordinator.confirm8  s   '#9:UVVw3347W'--/IJJ9#B#BB+,WXX 6dllC--**7+?+?@	O !!W%?%??))CCIN''( ,,^__%%i1E1EF))+E7#7#7@	22OOG$8$8 P I 33E7;O;OQWXJ
 	ENN+%%&78(4 *
 	
  	+I	s   (AG 	G5$G00G5N)r+   canonical_digestc                   ddl m} ddlm}	  || j                          |	| j                  j
                  j                  d   | j                  j                  j                  |||||||	      S )zFReserve the static reminder only after current policy re-verification.r   r  ) reserve_missing_checkin_reminderr  )registry_digestr   operator_approvalr+   re  )	r^   r   checkin_cli.customer_schedulerg  ri   r/  r   ra   r#   )
rC   missing_windowdestinationrh  r   ri  r+   re  r   rg  s
             r   rg  zGRegisteredCustomerDualCoachCoordinator.reserve_missing_checkin_reminderf  sf     	XR 	-T\\:/LL&&..q1LL**+'/1-

 
	
r   c                   ddl m} ddlm}  ||fi |}|y || j                        }| j
                  j                  d|j                  |j                  j                         |j                  |j                  j                         |j                  |j                  |j                  |j                  dd|j                         S )	z?Persist a deduped non-response review signal; this never sends.r   r  )non_response_review_candidateNmissing_checkin_reminder_review)r#   rk  reminder_reservation_idresponse_window_ends_atcorrelation_idr   r   r   z missing-checkin-reminder-review:rK  )r^   r   5checkin_cli.weekly_operations_schedule_host_review_r4rn  ri   rv   rW  r#   rk  rV  rp  rq  rr  r   r   r   )rC   reminderkwargsr   rn  r[  r   s          r   reminder_review_candidatez@RegisteredCustomerDualCoachCoordinator.reminder_review_candidate  s     	X	
 2(EfE	5dllC""))- ) 6 6"+":":"D"D"F+4+L+L+4+L+L+V+V+X"+":":"(..!'!5!5*0*@*@	 :):R:R9ST * 
 	
r   c                    t        |t              r#|| j                  j                  j                  k7  rt        d      y )Nz3customer key is not registered for this coordinator)rT   r"   ri   ra   r#   r   r   s     r   r   z8RegisteredCustomerDualCoachCoordinator._require_customer  s5    ,,@Q@Q@^@^0^+,abb 1_r   c                h    t        | d      st        d      t        | j                  dd            S )Nr   zdual-coach event is invalidr   Tr   )hasattrrs   _canonical_digestr   )r%   s    r   r   z4RegisteredCustomerDualCoachCoordinator._event_digest  s3    ul+9:: !1!1vD!1!QRRr   )ri   rM   rJ   rK   rJ   r$   )r#   r"   rJ   object | NonerJ   r   )rJ   ztuple[object, int, str])rJ   ztuple[str, int])r%   r$   r#   r"   rJ   rK   )r   r"   rJ   rK   )rJ   zMapping[str, object] | None)r%   r$   r#   r"   r   r$   rJ   rK   )rJ   zScheduleConfirmReceipt | None)r%   r$   r#   r"   r   r$   rJ   r)   )r%   r$   rZ  r)   rJ   r)   )rc  r!   rJ   r(   )rk  r   rl  r$   rh  r"   r   r"   ri  r"   r+   
int | Nonere  
str | NonerJ   r$   )rt  r$   ru  r$   rJ   r|  )r#   r"   rJ   rK   )r%   r$   rJ   r"   )r   r   r   r   ry   rt   r   propertyr   r   r   r   r   rw   r  r  r	  rx   r  r^  rd  schedule_confirm_handlerrg  rv  r   staticmethodr   r   r   r   rn   rn   ~   s!   !"L
S U UM4+-Z##H
.` X X#8
#
J@
DZ
v+
Z  ' *.'+

 

 
 
 
 '
 %
 

<

*0
	
8c S Sr   rn   z
privacy-v1@0000000000000000000000000000000000000000000000000000000000000000c                    t        j                  | ddd      }t        j                  |j	                  d            j                         S )zCHash a stable JSON representation used by sealed registry bindings.FTr   r   r   )r   r   hashlibsha256encode	hexdigest)valuer   s     r   rz  rz    s9     jjUdzZG>>'..12<<>>r   c                    t        j                  t        | j                               j	                  d            j                         S )Nr   )r  r  r"   resolver  r  )r   s    r   _path_digestr    s0    >>#dlln-44W=>HHJJr   c                      e Zd ZU dZded<   ded<   ded<   ded<   ded<   ded	<   ded
<    eddd      Zded<   ddZddZddZ	y)r`   z?Sealed durable identity for a registry-backed customer runtime.r"   customer_key_digestdata_root_digestrh  registry_versionactivation_digest0Literal['ordinary_v1', 'diagnostic_isolated_v1']r   r   NF)defaultreprcomparer$   _tokenc           	     >   | j                   | j                  | j                  | j                  | j                  f}| j
                  t        urt        d      t        d |D              rt        d      t        d |D              rt        d      | j                  r| j                  dvrt        d      t        | j                   | j                  | j                  | j                  | j                  | j                  d      }| j                  |k7  rt        d      y )	Nz%registered customer binding is sealedc              3  ^   K   | ]%  }t        |t               xs t        |      d k7   ' yw)@   N)rT   r"   r@   r<   r  s     r   r>   z:RegisteredCustomerBinding.__post_init__.<locals>.<genexpr>  s,     R6%:eS))=SZ2-==6s   +-z-registered customer binding digest is invalidc              3  @   K   | ]  }t        d  |D                yw)c              3  $   K   | ]  }|d v 
 yw0123456789abcdefNr   r<   chars     r   r>   zDRegisteredCustomerBinding.__post_init__.<locals>.<genexpr>.<genexpr>  s     Ded411e   N)rA   r  s     r   r>   z:RegisteredCustomerBinding.__post_init__.<locals>.<genexpr>  s     YRXsDeDDRXs   >   ordinary_v1diagnostic_isolated_v1z/registered customer binding metadata is invalidr  r  rh  r  r  r   z+registered customer binding digest mismatch)r  r  rh  r  r   r  _REGISTERED_BINDING_TOKENr   rA   r  r   rz  )rC   valuesexpecteds      r   rD   z'RegisteredCustomerBinding.__post_init__  s   $$!!  ""
 ;;77'(OPPR6RR'(WXXYRXYY'(WXX$$		9b(b'(YZZ$'+'?'?$($9$9#'#7#7$($9$9%)%;%;			
 (*'(UVV +r   c                    t        d      Nz1registered customer bindings are not serializablers   rB   s    r   __getstate__z&RegisteredCustomerBinding.__getstate__      KLLr   c                    t        d      r  r  rB   s    r   
__reduce__z$RegisteredCustomerBinding.__reduce__  r  r   rI   r{  )
r   r   r   r   r&   r   r  rD   r  r  r   r   r   r`   r`     sT    I
::4eUCFFCW<MMr   r`   c           
         t        d| i      }t        |      }t        ||||||d      }t        |||||||t              S )Nr#   r  )rz  r  r`   r  )	r#   	data_rootrh  r  r  r   r  r  r   s	            r   _make_registered_bindingr    sg     ,^\,JK#I.&#6 0. 0!2	
	N %!	 	r      
min_length
max_lengthc                      e Zd ZU  ed      Z edd      Zded<    edd      Zded<    edd      Z	ded	<   e
dd
       Ze
dd       Zy)TelegramAddressTr   r   r  r  r"   user_idchat_idtopic_idc                H    | j                   | j                  | j                  fS r9   )r  r  r  rB   s    r   keyzTelegramAddress.key  s    dllDMM::r   c                2    | j                   | j                  fS r9   )r  r  rB   s    r   	space_keyzTelegramAddress.space_key  s    dmm,,r   N)rJ   ztuple[str, str, str])rJ   ztuple[str, str])r   r   r   r   model_configr   r  r&   r  r  r  r  r  r   r   r   r  r    se    T*LA"5GS5A"5GS5Q26Hc6; ; - -r   r  c                  f    e Zd ZU  ed      Zded<    edd      Zded	<    ed
d      Zded<   y)CustomerScheduleTr  r   
daily_timer      geler   weekly_weekdayr      monthly_dayN)	r   r   r   r   r  r&   r   r  r  r   r   r   r  r    s4    T*L1+NC+b)K)r   r  c                     e Zd ZU dZ edd      ZdZded<    ed	      Z	d
ed<    eddd      Z
d
ed<    edd      Zded<    edd      Zd
ed<    edd      Zd
ed<    ed      Zded<    ed      Zded<    ed      Zded<    edd      Zded <    ed!d"#      Zd$ed%<    ed&d"#      Zd
ed'<   d(Zd)ed*<   d!Zd+ed,<   d!Zd$ed-<   d!Zd$ed.<   d!Zd$ed/<   d!Zd$ed0<   d!Zd$ed1<   d!Zd$ed2<   d!Zd3ed4<   d!Zd$ed5<   d!Zd$ed6<   d!Zd$ed7<   d!Z d$ed8<   d!Z!d3ed9<    ed!d"#      Z"d$ed:<   d!Z#d$ed;<   d!Z$d$ed<<   d!Z%d=ed><   d!Z&d?ed@<    e'dAB      dEdC       Z(dFdDZ)y!)GAdaptiveRegistrationInputsaJ  Versioned, owner-approved customer inputs for adaptive nutrition.

    The model deliberately keeps the approval envelope alongside the customer
    values. Callers may construct a value-only instance for validation; the
    administrative approval boundary fills and verifies the envelope before a
    document is persisted.
    Tforbidr   extraz1.0zLiteral['1.0']schema_version^[a-z0-9][a-z0-9_-]{2,63}$patternr"   r#   v1r   P   r  r  r  r      r  r   
meal_countr  budget_bandcooking_access(   )r  tuple[ProfileItem, ...]preferences
exclusions	allergiesin  z)tuple[CustomerTrainingScheduleEntry, ...]r1  N^[0-9a-f]{64}$r  r  r  rW   r  supersedes_digestFboolapprovedzTelegramAddress | Noneapproved_byapproved_at_kstactivation_receipt_idrh  owner_digestactivation_receipt_digestauthority_digestzdict[str, object] | None	authoritybase_policy_versionbase_policy_digestmeal_constraints_versionmeal_constraints_digestderived_constraintsderived_constraints_digestcatalog_versioncatalog_digestzdict[str, str] | Noneartifact_digestsz#dict[str, dict[str, object]] | Noneartifact_documentsafterr   c                    t        d | j                  D              }t        t        |            t        |      k7  rt	        d      | S )Nc              3  4   K   | ]  }|j                     y wr9   )r   r;   s     r   r>   zJAdaptiveRegistrationInputs.require_unique_training_days.<locals>.<genexpr>]  s     B+A4TYY+Ar]   z&training schedule dates must be unique)rb   r1  r@   setr   )rC   dayss     r   require_unique_training_daysz7AdaptiveRegistrationInputs.require_unique_training_days[  s=    B4+A+ABBs4y>SY&'(PQQr   c                   | j                   | j                  | j                  | j                  | j                  | j
                  t        | j                        t        | j                        t        | j                        | j                  D cg c]M  }|j                  j                         |j                  |j                  j                         |j                  dO c}d
S c c}w )z?Return the canonical digest preimage without approval metadata.)r   weekdayr   r2  )
r  r#   r   r  r  r  r  r  r  r1  )r  r#   r   r  r  r  rY  r  r  r  r1  r   rV  r  r   r2  )rC   r=   s     r   value_payloadz(AdaptiveRegistrationInputs.value_payloadb  s     #11 --||//++"11 0 01t/dnn- !22" 3D !II//1#|| II//1%)%7%7	 3"
 	
"s   AC$)rJ   r  )rJ   zdict[str, object])*r   r   r   r   r   r  r  r&   r   r#   r   r  r  r  r  r  r  r1  rW   r  r  r  r  r  rh  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r   r   r   r  r  '  s    T:L%*NN*&CDL#D!CGSCqQ'J'b9K91<NC<+0B+?K(?*/2*>J'>).")=I&=CHD@  t5FGFJG"8=NOsOHd*.K'."&OZ&(,:,"&OZ&#L*#,0z0#'j'*.I'.&**%)
)+/j/*.Z.4818-2!.
  #'OZ&!%NJ%.2+2>B;B'" #
r   r  c                     e Zd ZU  ed      Z eddd      Zded<    ed	d
      Zded<    edd      Z	ded<    edd      Z
ded<    edd      Zded<    edd      Zded<    edd      Zded<    ed	d      Zded<    ed	d      Zded<    ed	dd      Zded<    ed	d      Zded<    ed	d
      Zded<    ed	d d!      Zd"ed#<    ed	d
      Zded$<    ed	d
      Zded%<    ed	d&      Zded'<   y	)(CustomerProfileTr  u   미정r     r  r"   primary_goalN  r  r  r  starting_contextr      r  dietary_restrictionsr  food_preferencesdisliked_foods   supplementsr  r  r  r  r  r  r  r~  r  schedule_constraintsdigestion_contextr      float | Nonesleep_goal_hoursrecovery_goaltraining_contexti  coach_notes)r   r   r   r   r  r   r  r&   r  r  r  r	  r
  r  r  r  r  r  r  r  r  r  r  r   r   r   r  r  |  s/   T*Lh1ML#M#(%#HjH49"QS4T1T).rb)II&I05bR0P-P.3B2.NN+N+0+KK(K!&t!DNJD#DSAKA"4A!<J
<',Tc'J*J$)$5$IzI%*4A"%ElE %du EM:E#(%#HjH#DUCKCr   r  c                  z    e Zd ZU  ed      ZdZded<   dZded<    edd	
      Z	ded<    e
d      dd       Zy)AiProcessingConsentTr  Fr  grantedNzdate | Nonerecorded_onr  r  r  notice_versionr  r  c                d    | j                   r#| j                  | j                  st        d      | S )Nz6AI processing consent requires date and notice version)r  r  r  r   rB   s    r   require_auditable_grantz+AiProcessingConsent.require_auditable_grant  s-    <<T--5T=P=P'(`aar   )rJ   r  )r   r   r   r   r  r  r&   r  r   r  r   r  r   r   r   r  r    sH    T*LGT#K#!&t!CNJC'" #r   r  c                  4   e Zd ZU  ed      Z edd      Zded<    edd	      Zded
<    edd      Z	ded<    edd      Z
ded<    eddd      Zded<    eddd      Zded<    eddd      Zded<    edd      Zded<    edd      Zded <   y)!PlanWeekTr  r      r  r   weeki   i'  calories_kcalr  r  	protein_gr  r  r  meal_structureNr   r  r  r~  carbohydrate_gi  fat_gr  r  water_litersr  r  nutrition_focusrecovery_focus)r   r   r   r   r  r   r   r&   r!  r"  r#  r$  r%  r&  r'  r(  r   r   r   r  r    s    T*Lr"D#"#&1M31bS)Is).3qQ.ON+O!&te!DNJDdqU;E:;!&tb!AL,A"'"GOZG!&t!FNJFr   r  c                  r    e Zd ZU  ed      Zded<   ded<    edd      Zd	ed
<    ed      dd       Z	y)TwelveWeekPlanTr  r   	starts_onz#Literal['nutrition_90_training_10']focusr  r  ztuple[PlanWeek, ...]weeksr  r  c                    t        d | j                  D              t        t        dd            k7  rt        d      | S )Nc              3  4   K   | ]  }|j                     y wr9   r   r;   s     r   r>   z;TwelveWeekPlan.require_complete_sequence.<locals>.<genexpr>       2ztzr]   r      z'plan weeks must be exactly 1 through 12)rb   r-  r3  r   rB   s    r   require_complete_sequencez(TwelveWeekPlan.require_complete_sequence  s5    2tzz22eE!RL6II'(QRRr   N)rJ   r*  )
r   r   r   r   r  r&   r   r-  r   r3  r   r   r   r*  r*    s@    T*LO.."'2""EEE'" #r   r*  c                      e Zd ZU  edd      Z ed      Zded<    edd	
      Zded<   ded<   ded<   dZ	ded<   ded<    ee
      Zded<    ee      Zded<   ded<   ddZy)CustomerSpecTr  r  r  r  r"   r#   r   r  r  display_namer  enabledr  telegramNzTrainerAssignment | Nonetrainerr  schedule)default_factoryr  profiler  ai_processing_consentr*  planc                   | j                   }|j                  st        d      |j                  |j                  t
        k7  rt        dt
               	 t        j                  | j                  j                               }t        d |j                  D              t        t        dd            k7  rt        d      y# t        t        f$ r}t        d      |d}~ww xY w)	z=Validate only the customer-owned requirements for activation.z-customer AI processing consent is not grantedNz8customer AI processing consent must use current version zcustomer inline plan is invalidc              3  4   K   | ]  }|j                     y wr9   r0  r;   s     r   r>   zGCustomerSpec.validate_local_activation_prerequisites.<locals>.<genexpr>  r1  r]   r   r2  z2customer inline plan must contain exactly 12 weeks)r=  r  r   r  r  CONSENT_VERSIONr*  r   r>  r   rs   r?   rb   r-  r3  )rC   consentr>  r   s       r   'validate_local_activation_prerequisitesz4CustomerSpec.validate_local_activation_prerequisites  s    ,,'(WXX&'*@*@O*S'J?J[\ 	T!001E1E1GHD 2tzz22eE!RL6II'(\]] J :& 	T'(IJPSS	Ts   -C C!CC!rI   )r   r   r   r   r  r   r#   r&   r6  r9  r  r<  r  r=  rC  r   r   r   r5  r5    sx    T:L&CDL#Dr:L#:M(,G%,$_EG_E16GZ1[.[
^r   r5  c                      e Zd ZU  ed      Zded<   dZded<    edd	
      Zded<   ded<   ded<    e	d      dd       Z
	 d	 	 	 ddZddZy)RegistryDocumentTr  z
Literal[1]r   r  r  registry_modeNr  r  r  diagnostic_session_digestr  ownerztuple[CustomerSpec, ...]	customersr  r  c                   | j                   dk(  r| j                  "t        d      | j                  t        d      t        d | j                  D              }t        d | j                  D              }t        d | j                  D              }t        t        |            t        |      k7  rt        d      t        t        |            t        |      k7  rt        d      t        t        |            t        |      k7  rt        d	      t        d
 | j                  D              }t        |      dkD  rt        d      |D ]  }| j                  |        | S )Nr  z9diagnostic registry requires a diagnostic session bindingz;ordinary registry cannot carry a diagnostic session bindingc              3  4   K   | ]  }|j                     y wr9   r`  r;   s     r   r>   z=RegistryDocument.require_unique_boundaries.<locals>.<genexpr>  s     B>4T&&>r]   c              3  H   K   | ]  }|j                   j                    y wr9   )r8  r  r;   s     r   r>   z=RegistryDocument.require_unique_boundaries.<locals>.<genexpr>  s     G$--++    "c              3  H   K   | ]  }|j                   j                    y wr9   )r8  r  r;   s     r   r>   z=RegistryDocument.require_unique_boundaries.<locals>.<genexpr>  s     J>4t}}..>rM  zcustomer keys must be uniquez*customer Telegram addresses must be uniquez'customer Telegram spaces must be uniquec              3  :   K   | ]  }|j                   s|  y wr9   r7  r;   s     r   r>   z=RegistryDocument.require_unique_boundaries.<locals>.<genexpr>  s     H4<<s   r   )pilot supports only one external customer)rF  rG  r   rb   rI  r@   r  validate_enabled_customer)rC   keys	addressesspacesr7  customers         r   require_unique_boundariesz*RegistryDocument.require_unique_boundaries  s4   !99--5+O  ++7'M  B4>>BBGGG	J4>>JJs4y>SY&'(FGGs9~#i.0'(TUUs6{s6{*'(QRRHHHw<!'(STTH**84  r   c                l    | j                   ||fndz   }t        d |D              dkD  rt        d      y)zEnforce the one-external-customer pilot boundary.

        Disabled entries remain parseable for historical/test data and do not
        count toward the one-enabled-customer limit.
        Nr   c              3  4   K   | ]  }|j                     y wr9   rP  r;   s     r   r>   zDRegistryDocument.validate_pilot_customer_boundary.<locals>.<genexpr>  s     2	t||	r]   r   rQ  )rI  sumr   )rC   r[  rI  s      r    validate_pilot_customer_boundaryz1RegistryDocument.validate_pilot_customer_boundary  s@     NNi6KylQST	2	22Q6'(STT 7r   c                   |j                   sy|j                          | j                  j                  |j                  j                  k(  s-| j                  j
                  |j                  j
                  k(  rt        d      y)zDValidate owner-inclusive identity and local activation requirements.Nz2owner and customer Telegram identities must differ)r7  rC  rH  r  r8  r  r   )rC   ra   s     r   rR  z*RegistryDocument.validate_enabled_customer
  s_    ||446::>>T]]...$**2F2F$--JaJa2a'(\]] 3br   )rJ   rE  r9   )r[  zCustomerSpec | NonerJ   rK   )ra   r5  rJ   rK   )r   r   r   r   r  r&   rF  r   rG  r   rW  r[  rR  r   r   r   rE  rE    sx    T*LFSMCS,1$HY,ZzZ'''" #8 *.U&U 
U^r   rE  c                      e Zd ZU ded<   ded<   dZded<   ddZedd	       Zedd
       Zedd       Z	edd       Z
edd       ZddZy)rM   r5  ra   r   r  Nz RegisteredCustomerBinding | Noner_   c                    | j                   }t        |t              st        d      |j	                         rt        d      y )Nz!customer data root must be a path+customer data root symlinks are not allowed)r  rT   r   r   
is_symlink)rC   rr   s     r   rD   zCustomerRuntime.__post_init__  s<    ~~$%'(KLL??'(UVV r   c                6    | j                   j                         S r9   )r  r  rB   s    r   r/  zCustomerRuntime.customer_root   s    ~~%%''r   c                <    | j                   dz  j                         S )Nwizardr/  r  rB   s    r   wizard_rootzCustomerRuntime.wizard_root$  s    ""X-6688r   c                <    | j                   dz  j                         S )Nznutrition-plansrd  rB   s    r   ru   z$CustomerRuntime.nutrition_plans_root(  s    ""%66??AAr   c                H    | j                   t        d      | j                   S )Nz*customer runtime has no registered binding)r_   r   rB   s    r   r   z"CustomerRuntime.registered_binding,  s"    <<'(TUU||r   c                J    | j                   | j                   j                  S dS )N
standalone)r_   r   rB   s    r   r   zCustomerRuntime.mode2  s     $(LL$<t||  N,Nr   c                    t        d|| j                  j                  j                  z
  j                        }| j                  j                  j
                  t        d|dz           S )Nr      r   )maxra   r>  r+  r  r-  min)rC   dayelapseds      r   	plan_weekzCustomerRuntime.plan_week6  sK    a#		 8 88>>?yy~~##CGqL$9::r   rI   r}  )rJ   r`   rL   )rn  r   rJ   r  )r   r   r   r&   r_   rD   r  r/  re  ru   r   r   rp  r   r   r   rM   rM     s    
O04G-4W ( ( 9 9 B B  
 O O;r   c                  "    e Zd ZU ded<   ded<   y)CustomerRegistryr  rH  ztuple[CustomerRuntime, ...]rI  Nr-   r   r   r   rr  rr  :  s    **r   rr  c                    t        | |d      S )zEParse a private ordinary registry and derive profile-contained roots.Fallow_diagnostic)_load_customer_registry)r   profile_roots     r   load_customer_registryrx  @  s     #4NNr   )session_digestc                  t        |t              r t        |      dk7  st        d |D              rt	        d      	 t        | |d      }| j                         }t        j                  |      }|j                  dk7  rt	        d	      |j                  |k7  rt	        d
      |S # t        $ r  t        $ r}t	        d      |d}~ww xY w)zILoad the explicitly marked diagnostic registry, never via ordinary paths.r  c              3  $   K   | ]  }|d v 
 ywr  r   r  s     r   r>   z<load_diagnostic_runtime_customer_registry.<locals>.<genexpr>Q  s     I.$t--.r  z&diagnostic session binding is requiredTrt  zdiagnostic registry is invalidNr  5ordinary registry is not valid for diagnostic loadingz,diagnostic registry session binding mismatch)rT   r"   r@   rA   r   rv  r?   
read_bytesrE  model_validate_jsonrF  rG  )r   rw  ry  registryr   rawr   s          r   )load_diagnostic_runtime_customer_registryr  F  s     ~s+~"$I.II#$LMMO*4PTU
 //
C33C8H!99#$[\\))^;#$RSSO !  O#$DE3NOs   B& &C	8CC	c               ~   t        | |      rt        d      |j                         }| j                         }|j                  |      st        d      | j	                         }t
        j                  |      }|r|j                  dk7  rt        d      |s|j                  dk(  rt        d      t        ||||      S )Nz!registry symlinks are not allowedzregistry escapes the profiler  r|  5diagnostic registry is not valid for ordinary loading)	_has_symlinkr   r  is_relative_tor}  rE  r~  rF  _registry_from_document)r   rw  ru  resolved_rootresolved_registryr  r   s          r   rv  rv  c  s     D,'#$GHH ((*M++M:#$BCC
//
C33C8HH226NN#$[\\ 6 6:R R#$[\\"8S,NNr   c                    t         j                  |       }|j                  dk(  rt        d      t	        || ||j                  d            S )zEParse retained descriptor bytes under an already pinned profile root.r  r  T)strict)rE  r~  rF  r   r  r  )r  rw  r   s      r   load_customer_registry_bytesr  x  sQ    33C8H!99#$[\\"#|\%9%9%9%F r   c           	     j   t        j                  |      j                         }g }t               }| j                  D ]V  }|j                         dz  dz  |j                  z  }t        ||      rt        d      |j                         r|j                         st        d      |j                         }	|	j                  |      st        d      |	|v rt        d      |j                  |	       t        |dd       t        |dd       t        |d	d       |j                  d
}
t        |dd       }|xs t        |
      }t!        |j                  |	|t#        | j$                        || j&                        }|j)                  t+        ||	|             Y t-        | j.                  t1        |            S )NdatarI  r_  z&customer data root must be a directoryz&customer data root escapes the profilez"customer data roots must be uniquer  r  r  )r  r  r  r#   )r#   r  rh  r  r  r   )r  r  r  r  rI  absoluter#   r  r   r   is_dirr  r  addgetattrrz  r  r"   r   rF  rW  rM   rr  rH  rb   )r   r  rw  r  rh  runtimesresolved_data_rootsra   r[  r  activation_payloadreceipt_digestr  r_   s                 r   r  r    s    nnS)335O&(H%(U"" ))+f4{BTEVEVV		<0'(UVVi&6&6&8'(PQQ%%'	''6'(PQQ++'(LMM	*%,T3JD%Q)07RTX)Y '.@$ G --	
 !'BDI*S.?@R.S***+ !1!12/''
 	iAB9 #: HNNE(O<<r   c                    |j                         }| j                         }|j                         s|j                  |      sy|}|j                  |      j                  D ]  }||z  }|j                         s y y)NTF)r  r`  r  relative_toparts)r   rw  rr   targetcurrentparts         r   r  r    sr      "D]]_F 5 5d ;G""4(..4 / r   )
ri   rM   rY   r$   r4   ztuple[object, ...]r5   r"   rJ   r/   )r  r$   rJ   r"   )r   r   rJ   r"   )r#   r"   r  r   rh  r"   r  r"   r  r"   r   r  rJ   r`   )r   r   rw  r   rJ   rr  )r   r   rw  r   ry  r  rJ   rr  )r   r   rw  r   ru  r  rJ   rr  )r  bytesrw  r   rJ   rr  )
r   rE  r  r  rw  r   r  r   rJ   rr  )r   r   rw  r   rJ   r  )>r   
__future__r   r  r   r   dataclassesr   r   datetimer   r   pathlibr   collections.abcr	   typingr
   r   pydanticr   r   r   r    weekly_operations_domain_trainerr   r   r?   r   r   r!   r(   r/   rl   rn   rA  r$   r  _DIGEST_ZEROrz  r  r`   r  r"   ProfileItemr  r  r  r  r  r  r*  r5  rE  rM   rr  rx  r  rv  r  r  r  r   r   r   <module>r     s   J "   	 (   # % B B ^	J 	M
 M $d#  $ $d#. . $.
 $d#  $:777  	7
 7 7rjS jSV "H ?K $d#.M .M $.Mb  	
   ; B UaC@@A-i - *y *Q
 Q
jDi D*) Gy GY ^9 ^<7^y 7^t $d#$; $; $$;L $d#+ + $+
O "&	
 	
 :O
OO 	O
 O*&=&=	&= &= 	&=
 &=R
r   