
    i j                         d dl Z d dlZd dlmZ d dlmZ d dlmZ  ed            e e j        d                    Z	d	Z
d
edefdZdS )    N)Path)OpenAI)load_dotenvT)overrideOPENAI_API_KEY)api_keyuq  You are a pharma CAPA (Corrective and Preventive Action) planning engine.

Based on the approved root cause and exception data, generate a complete CAPA plan.

Return JSON only with this exact structure:
{
  "deviation_id": string,
  "batch_id": string or null,
  "product_name": string or null,
  "plant": string or null,
  "severity": one of ["Critical", "High", "Medium", "Low"],
  "approved_root_cause": {
    "summary": string,
    "approved_by": string,
    "evidence_coverage": string,
    "linked_cluster": string
  },
  "capa_actions": [
    {
      "capa_id": string,
      "action": string,
      "type": one of ["Preventive", "Corrective", "Effectiveness"],
      "owner": string,
      "due_date": string,
      "verification_method": string,
      "status": one of ["Draft", "Pending", "In Progress", "Completed", "Verified", "Not Started"]
    }
  ],
  "impact_assessment": {
    "pre_capa_risk": one of ["Critical", "High", "Medium", "Low"],
    "residual_risk": one of ["Critical", "High", "Medium", "Low"],
    "affected_batches": array of strings,
    "total_product_units": string
  },
  "effectiveness_tracking": {
    "methodology": string,
    "monitoring_start": string,
    "monitoring_end": string,
    "recurrence_rate": {
      "value": string,
      "target": string
    },
    "actions_closed": {
      "value": string,
      "note": string
    },
    "audit_findings": {
      "value": number,
      "note": string
    },
    "verification_due": {
      "value": string,
      "note": string
    }
  },
  "action_verification_status": [
    {
      "capa_id": string,
      "action": string,
      "status": one of ["Verified", "In Progress", "Not Started"],
      "progress": number 0-100
    }
  ],
  "pre_closure_checklist": {
    "root_cause_verified_by_qa": true or false,
    "no_recurrence_in_monitoring_period": true or false,
    "equipment_re_qualified": true or false,
    "all_corrective_actions_closed": true or false,
    "regulatory_submission_ready": true or false,
    "training_records_updated": true or false
  },
  "plan_approval": {
    "status": one of ["Pending", "Approved", "Rejected"],
    "approved_by": null,
    "approved_at": null,
    "send_for_execution": false
  }
}

CAPA rules:
- Always generate at least 3 actions — one Preventive, one Corrective, one Effectiveness
- Corrective: fixes the immediate problem
- Preventive: stops it from happening again
- Effectiveness: checks if the fix actually worked
- due_date format: YYYY-MM-DD
- owner should be a role name like QA Manager, Engineering Lead, Production Supervisor
- capa_id format: CP-XXXX where XXXX is a 4 digit number starting from 9901
- pre_capa_risk is always higher than residual_risk
- plan_approval: always start with status Pending, approved_by null, send_for_execution false

effectiveness_tracking rules:
- recurrence_rate.value: "0%" initially, target "< 5%"
- actions_closed.value: format "X/Y" based on completed vs total actions
- actions_closed.note: "By due date"
- audit_findings.value: 0 initially, note "Post-CAPA"
- verification_due.value: days remaining e.g. "14d", note "Remaining"

action_verification_status rules:
- one entry per capa_action
- Verified = 100%, In Progress = 60%, Not Started = 0%
- First action starts as Verified if corrective action is immediate fix

pre_closure_checklist rules:
- root_cause_verified_by_qa: true if RCA was approved
- no_recurrence_in_monitoring_period: true if monitoring just started
- equipment_re_qualified: true if equipment was fixed
- all_corrective_actions_closed: false initially
- regulatory_submission_ready: false initially
- training_records_updated: false initially

Data to analyze:
<content>
datareturnc                 .  K   	 t          j        | d          }t                              d|d d                   }t          j        j                            ddddd	|dgd
did          }|j        d         j	        j
        }t          j        |          }d|d<   |S # t           j        $ r.}dt          |          g i i g ddddddddd d dddcY d }~S d }~wt          $ r.}dt          |          g i i g ddddddddd d dddcY d }~S d }~ww xY w)N   )indentz	<content>i@  zgpt-4osystemzGYou are a pharma CAPA planning engine. Return JSON only. No extra text.)rolecontentusertypejson_objectr   )modelmessagesresponse_formattemperature	completedstatusparse_errorF)root_cause_verified_by_qa"no_recurrence_in_monitoring_periodequipment_re_qualifiedall_corrective_actions_closedregulatory_submission_readytraining_records_updatedPending)r   approved_byapproved_atsend_for_execution)r   errorcapa_actionsimpact_assessmenteffectiveness_trackingaction_verification_statuspre_closure_checklistplan_approvalr%   )jsondumpsCAPA_PROMPTreplaceclientchatcompletionscreatechoicesmessager   loadsJSONDecodeErrorstr	Exception)r	   data_strpromptresponserawresultes          AC:\Users\Terasoftware\OneDrive\Desktop\faahhh\fyndo\fyndo\capa.pygenerate_caparA   }   s     F
:d1---$$[(5D5/BB;*11 %h 
 #% 	 $]3 2 
 
  q!)1C&x 
 
 
#VV!#&(*,-26;*/16/4,1& & $##&+	 
 
 	
 	
 	
 	
 	
 	
,  
 
 
VV!#&(*,-26;*/16/4,1& & $##&+	 
 
 	
 	
 	
 	
 	
 	

s0   BB! !D0#CDD&#D	DD)osr,   pathlibr   openair   dotenvr   getenvr0   r.   dictrA        r@   <module>rJ      s    				                    T    			"233	4	4	4pfG
d G
t G
 G
 G
 G
 G
 G
rI   