
    j                          d dl mZmZmZmZ d dlmZ d dlmZ dZ	 G d de
      Z G d de      Z G d	 d
e      Z G d de      ZdededefdZy)    )AnyDictListOptional)Request)JSONResponsecodemessagec                   N     e Zd ZdZ	 d	dddedededeeeef      f fdZ	 xZ
S )
AppErroruo  Application-level error mapped to JSON response by ``app_error_handler``.

    ``details`` (optional, kw-only) is merged into the ``error`` payload by the
    handler — used by subclasses (e.g. ``StaleUpstreamError``) that need to
    surface structured remediation metadata. Existing call sites that omit
    ``details`` are unaffected: the response shape stays
    ``{"error": {"code", "message"}}``.

    Reserved keys (``code`` / ``message``) cannot appear in ``details`` —
    fail-fast at construction time. The handler also enforces base-fields-win
    on merge as defense in depth (review iter1 IMPORTANT).
    N)detailsr
   r   status_coder   c                    |r/|D cg c]  }|t         v s| }}|rt        dt          d|      || _        || _        || _        |rt        |      ni | _        t        | !  |       y c c}w )Nz*AppError details cannot use reserved keys u	    — got )	_RESERVED_DETAIL_KEYS
ValueErrorr
   r   r   dictr   super__init__)selfr
   r   r   r   kinvalid	__class__s          E/Users/manta/Documents/Projects/TheRoad-I1/backend/app/core/errors.pyr   zAppError.__init__   s     ")H'QQ2G-Gq'GH @,-YwkC  	&(/tG}R! Is
   A,A,)i  )__name__
__module____qualname____doc__strintr   r   r   r   __classcell__r   s   @r   r   r   
   sT    " 	" -1"" " 	" $sCx.)" "    r   c                   j     e Zd ZdZdddddddedededee   d	ee   d
eee      dedef fdZ xZS )StaleUpstreamErroru(  D6 §4.8 — preflight detection: upstream cp is stale.

    Raised by ``app.services.dispatcher_preflight.check_bg_catalog_freshness``
    when ``background_master_plan`` and consumer manifests disagree on
    ``bg_catalog_hash`` / ``shot_binding_hash``, when a consumer manifest is
    missing under D6 mode, or when a manifest file is corrupt.

    HTTP 422. Direct attributes (``upstream`` / ``expected_*`` / ``observed_*``
    / ``missing_in_render`` / ``remediation``) are also surfaced via
    ``self.details`` for the handler to serialize.
    N )expected_shot_binding_hashobserved_shot_binding_hashmissing_in_renderremediationr   upstreamexpected_bg_catalog_hashobserved_bg_catalog_hashr'   r(   r)   r*   r   c                ,   || _         || _        || _        || _        || _        t        |xs g       | _        || _        ||||d}	|||	d<   |xs d|	d<   | j                  rt        | j                        |	d<   t        
| %  d|xs d| d|		       y )
N)r+   r,   r-   r*   r'   r&   r(   r)   STALE_UPSTREAMzSTALE_UPSTREAM upstream=  r
   r   r   r   )
r+   r,   r-   r'   r(   listr)   r*   r   r   )r   r+   r,   r-   r'   r(   r)   r*   r   r   r   s             r   r   zStaleUpstreamError.__init__;   s     !(@%(@%*D'*D'!%&7&=2!>& !(@(@&	#
 &14NG014N4TRTG01!!+/0F0F+GG'(!D!9(D	 	 	
r#   )	r   r   r   r   r   r   r   r   r!   r"   s   @r   r%   r%   .   s    
$ 594815%
 %
 #&	%

 #&%
 %-SM%
 %-SM%
 $DI.%
 %
 %
 %
r#   r%   c                   N     e Zd ZdZdddedee   dedeeef   def
 fd	Z xZS )
VisibleStagingDriftErroru  shot_director.visible_entity_ids ↔ shot_staging.camera_direction dual SOT
    drift 가 scene_detail 진입 직전에 감지되었음을 알리는 fail-fast.

    shot_staging 의 camera_direction NL 에 명시적 off-camera/off-screen/화면 밖
    phrase 가 있는데 그 인접의 인물 이름이 director.visible 에 남아 있으면 drift.
    auto-fix 안 함 (consumer-side SOT 변조 위험) — 운영자가 shot_director force
    재실행 또는 shot_staging force 재실행 으로 명시적 reconciliation 결정.

    HTTP 422. Direct attributes (``shot_label`` / ``visible`` / ``camera_direction``
    / ``drift_entities`` / ``remediation``) 도 ``self.details`` 로 serialize.
    r&   )r*   
shot_labelvisiblecamera_directiondrift_entitiesr*   c                P   || _         t        |      | _        || _        t	        |      | _        |xs d| _        |t        |      |t	        |      | j                  d}dj                  d t        |j                               D              }t        | -  d| d| dd|	       y )
Nu   shot_director force 재실행 (description-level gaze/offscreen 제외 재산출) 또는 shot_staging force 재실행 (camera_direction 재기획) 후 scene_detail 재진입.)r5   r6   r7   r8   r*   z, c              3   2   K   | ]  \  }}| d | d  yw)()N ).0sidnms      r   	<genexpr>z4VisibleStagingDriftError.__init__.<locals>.<genexpr>   s%      
*HwsBse1RDN*Hs   VISIBLE_STAGING_DRIFTu`   : shot_director.visible 와 shot_staging.camera_direction 사이 dual SOT drift — staging 이 uV    를 명시적 off-camera 처리했으나 visible 에 남아 있음. auto-fix 안 함.r0   r1   )r5   r2   r6   r7   r   r8   r*   joinsorteditemsr   r   )	r   r5   r6   r7   r8   r*   r   
drift_reprr   s	           r   r   z!VisibleStagingDriftError.__init__p   s     %G} 0">2& 
* 	 %G} 0">2++#
 YY 
*01E1E1G*H
 

 	(, J, ,-
  	 
	
r#   )	r   r   r   r   r   r   r   r   r!   r"   s   @r   r4   r4   c   sU    
& '
 '
 c	'

 '
 S#X'
 '
 '
r#   r4   c                   D     e Zd ZdZdedededeeeef      f fdZ	 xZ
S )ShotStagingOrientationErroru  Patch C / Area A — content_surface / reflective_surface element 의
    orientation 이 max_attempts (3회) 모두 빈 값으로 남음.

    HTTP 422. shot_staging step fail. 운영자가 analysis_dispatch
    mode=force 로 step 수동 재실행.

    raise 는 shot_staging.py 의 batch loop 안 `call_structured` try/
    except Exception **밖**에서 실행되어야 broad except 에 swallow 되지
    않는다 — umbrella spec Area A § 4.2 참조.
    	batch_numtotal_batchesattempts
violationsc                    || _         || _        || _        t        |      | _        |||t        |      d}t
        |   dd| d| dt        | j                         d| d	d|	       y )
N)rI   rJ   rK   rL    SHOT_STAGING_ORIENTATION_MISSINGzshot_staging batch /z: zT element(s) with content_surface/reflective_surface class missing orientation after z
 attempts.r0   r1   )rI   rJ   rK   r2   rL   r   r   len)r   rI   rJ   rK   rL   r   r   s         r   r   z$ShotStagingOrientationError.__init__   s     #* z* #* z*	#
 	3%i[-t'( )F*J(
  	 
	
r#   )r   r   r   r   r    r   r   r   r   r   r!   r"   s   @r   rH   rH      sG    	
 
 	

 
 c3h(
 
r#   rH   requestexcreturnc                 *  K   |j                   |j                  d}|j                  rJ|j                  j                         D ci c]  \  }}|t        vs|| }}}|j                  |       |}n|}t        |j                  d|i      S c c}}w w)aU  Serialize AppError to ``{"error": {...}}`` JSON.

    Base ``code`` / ``message`` always win over ``details`` to prevent a
    subclass from accidentally shadowing them via ``details={"code": ..., ...}``
    (review iter1 IMPORTANT). ``StaleUpstreamError`` and other subclasses must
    surface remediation metadata under disjoint keys.
    r	   error)r   content)r
   r   r   rE   r   updater   r   )rQ   rR   baser   vmergederrs          r   app_error_handlerr\      s      HH5D
{{ $';;#4#4#6Y#641a!CX:X!Q$#6Yd$OO#  Zs   ABBB8BN)typingr   r   r   r   fastapir   fastapi.responsesr   r   	Exceptionr   r%   r4   rH   r\   r=   r#   r   <module>ra      sg    , ,  * , !"y !"H2
 2
j4
x 4
n)
( )
XW 8  r#   