o
    i j                     @   sh   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d ee ddZ	d	Z
d
edefd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                    s"  z9t j| dd}td|d d }tjjjddddd	|dgd
didd}|jd j	j
}t |}d|d< |W S  t jyf } zdt|g i i g ddddddddd d dddW  Y d }~S d }~w ty } zdt|g i i g ddddddddd d dddW  Y d }~S d }~w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e r>   (/var/www/html/fyndo/pharma/fyndo/capa.pygenerate_capa}   s~   

		r@   )osr*   pathlibr   openair   dotenvr   getenvr.   r,   dictr@   r>   r>   r>   r?   <module>   s    
s