
    r j\I                        d dl Z d dlZd dlmZ d dlmZ d dlmZ d dlm	Z	m
Z
 d dlmZ d dlmZ d dlmZmZmZmZmZmZ d d	lmZ d d
lmZ d dlmZ  ed            e e j        d                    Z ed          Ze                    d           dZdede fdZ!de"de"fdZ#de"de defdZ$de"de de"fdZ%dS )    N)Path)OpenAI)A4)getSampleStyleSheetParagraphStyle)inch)colors)SimpleDocTemplate	ParagraphSpacerTable
TableStyle
HRFlowable)datetime)Request)load_dotenvT)overrideOPENAI_API_KEY)api_keyreports)exist_oku  You are a senior pharma quality investigator writing a GMP-compliant investigation report.

STRICT RULES — NEVER BREAK THESE:
1. NEVER say product was not impacted without checking LIMS results first
2. If ANY LIMS result shows Status=Fail — impact_assessment MUST say product was impacted with exact test name and value
3. NEVER use generic phrases — always use exact values from the data
4. Severity MUST come from Deviation Report severity field — not your own judgment
5. ref_id MUST come from Deviation_ID in the Deviation Report
6. Duration MUST be calculated from Equipment Log timestamps — not estimated
7. Root cause MUST reference exact maintenance log observations — thermocouple, calibration dates, drift values
8. Operator MUST be included from Equipment Log Operator_ID field
9. Batch disposition MUST come from Deviation Report Batch_Disposition field
10. CAPA actions MUST reference actual work order IDs and actions from Maintenance Log

Return JSON only with this exact structure:
{
  "report_metadata": {
    "ref_id": string,
    "revision": "Rev 01",
    "status": "Audit Ready",
    "severity": one of ["Critical", "High", "Medium", "Low"],
    "generated_date": string,
    "batch_id": string,
    "product_name": string,
    "plant": string,
    "confidential": true
  },
  "ai_generated_summary": string,
  "approval_workflow": {
    "qa_reviewer": {
      "name": string,
      "status": one of ["Approved", "Pending", "Rejected"],
      "note": string or null
    },
    "qa_head": {
      "name": string,
      "status": one of ["Approved", "Pending Final Sign Off", "Rejected"]
    }
  },
  "compliance_tags": array of strings,
  "sections": {
    "incident_overview": {
      "batch_number": string,
      "incident_date": string,
      "deviation_type": string,
      "department": string
    },
    "detected_deviations": [
      {
        "signal_exception": string,
        "duration": string,
        "peak_value": string,
        "limit": string,
        "is_deviation": true or false
      }
    ],
    "executive_summary": string,
    "deviation_description": string,
    "timeline": [
      {
        "timestamp": string,
        "event": string,
        "severity": one of ["critical", "warning", "info"]
      }
    ],
    "scope_of_review": string,
    "exceptions_summary": string,
    "root_cause_analysis": {
      "probable_cause": string,
      "methodology": string,
      "conclusion": string
    },
    "capa_summary": string,
    "impact_assessment": string,
    "conclusion": string,
    "regulatory_compliance": [
      {
        "standard": string,
        "status": one of ["Compliant", "Non-Compliant", "Under Review"]
      }
    ]
  },
  "compliance_checklist": [
    {
      "standard": string,
      "description": string,
      "status": one of ["pass", "warn", "fail"]
    }
  ],
  "evidence_coverage_score": number 0-100,
  "confidence_label": one of ["High Confidence", "Medium Confidence", "Low Confidence"],
  "ai_insight": string,
  "export_options": ["Export as PDF", "Export as Word", "Submit to Regulatory"]
}

Section writing rules:

ref_id: use Deviation_ID from Deviation Report exactly e.g. DEV-2024-0312
severity: copy exactly from Deviation Report Severity field

executive_summary (4-5 sentences):
- Name exact batch, product, plant, date
- Name exact parameters that deviated with exact values and limits
- Reference exact equipment ID
- State LIMS outcome — if assay failed state exact % and OOS reference
- State batch disposition from Deviation Report

deviation_description (5-6 sentences):
- Exact timestamp of first deviation from Equipment Log
- Exact operator ID from Equipment Log
- Progressive temperature rise with timestamps from Equipment Log
- Exact peak value reached
- What action was taken and when — from Deviation Report Immediate_Actions

detected_deviations duration:
- Calculate from Equipment Log — time from first Alert status to process stopped
- Do NOT estimate — use actual timestamps

root_cause_analysis.probable_cause:
- Reference exact equipment ID
- Reference calibration due date and overdue days from Maintenance Log
- Reference thermocouple drift value (+X°C) from Maintenance Log breakdown inspection
- Reference work order ID

root_cause_analysis.conclusion (4-5 sentences):
- Name the exact root cause with evidence
- Reference Maintenance Log dates and observations
- Reference Equipment Log notes at Alert rows
- Reference calibration overdue status

impact_assessment — CRITICAL RULE:
- CHECK LIMS results first — if any Status=Fail → product WAS impacted
- State exact test name, result value, specification, OOS reference number
- State batch disposition — HOLD or released
- If assay failed — state this clearly: "Assay result of X% is below specification of Y%-Z%"
- NEVER say "no impact" if LIMS has any Fail result

capa_summary:
- List actual CAPA actions from Maintenance Log Action_Taken field
- Reference work order IDs
- Reference new parts installed
- Reference requalification report if available

conclusion:
- State current batch status from Deviation Report Batch_Disposition
- State OOS investigation reference if LIMS failed
- State whether equipment was returned to service

Data to generate report from:
<content>
requestreturnc                 P    t          | j                                      d          S )N/)strbase_urlrstrip)r   s    CC:\Users\Terasoftware\OneDrive\Desktop\faahhh\fyndo\fyndo\report.pyget_base_urlr       s!    w  '',,,    datac                   K   	 t          j        | d          }t                              d|d d                   }t          j        j                            ddddd	|dgd
did          }|j        d         j	        j
        }t          j        |          }|S # t          $ r}dt          |          dcY d }~S d }~ww xY w)N   )indentz	<content>i'  zgpt-4osystemu  You are a senior pharma quality investigator.
CRITICAL INSTRUCTIONS:
- Always check LIMS results before writing impact assessment
- If LIMS has any Fail result — product was impacted — say so with exact values
- Never say product was not impacted without evidence
- Use exact values from data — no generic statements
- Severity comes from Deviation Report — not your judgment
- ref_id comes from Deviation_ID in Deviation Report
Return JSON only. No extra text.)rolecontentusertypejson_objectr   )modelmessagesresponse_formattemperatureerror)statusr0   )jsondumpsREPORT_PROMPTreplaceclientchatcompletionscreatechoicesmessager(   loads	Exceptionr   )r"   data_strpromptresponserawresultes          r   generate_report_jsonrD      s      !4:d1---&&{HVeV4DEE;*11 % $  #% $ $]3+ 2 
 
0 q!)1C 4 4 4!CFF333333334s   BB 
C&B=7C=Creportfilenamec                 
  &'( t           |z  }t          t          |          t          dt          z  dt          z  dt          z  dt          z            }t                      }g (t          j        d          }t          j        d          }t          j        d          }t          d|d         dd	|d
d          }t          d|d         d|d          }	t          d|d         dd	|dd          't          d|d         d|dd          &t          d|d         d|d	dd          }
| 	                    di           }| 	                    di           }| 	                    dg           }|	                    dd           
                                }(                    t          d!| d"|                     (                    t          d#|	                    d$d%           d&|	                    d'd(           d&|	                    d)          rd*nd+ |	                     (                    t          d,|	                    d-d.           d/|	                    d0t          j                                        d1                     |	                     (                    t!          d2d                     d3|	                    d4d5          d6|	                    d7d5          gd8|	                    d9d5          d:|gg}t#          |d;t          z  d<t          z  d;t          z  d<t          z  g=          }|                    t'          d>d?d@|fdAdBdCdDd?d@|fdEd?d@dFt          j        dG          fdHg                     (                    |           (                    t!          d2d                     (                    t)          dId2t          j        dG          J                     | 	                    dKd+          }|ri(                    t!          d2d                     (                    t          dL'                     (                    t          |&                     &'(fdM}|	                    dNi           }|r(                    t!          d2d                     (                    t          dO'                     (                    t)          dIdFt          j        dG          J                     (                    t!          d2d                     g dP|	                    dQd5          |	                    dRd5          |	                    dSd5          |	                    dTd5          gg}t#          |dUt          z  dUt          z  dt          z  dUt          z  g=          }|                    t'          d>d?dVt          j        dG          fdWdCdDd?d@|fdEd?d@dFt          j        dG          fdXg                     (                    |           |	                    dYg           }|rǉ(                    t!          d2d                     (                    t          dZ'                     (                    t)          dIdFt          j        dG          J                     (                    t!          d2d                     g d[g}|D ]k}|                    |	                    d\d5          |	                    d]d5          |	                    d^d5          |	                    d_d5          g           lt#          |d<t          z  d;t          z  d`t          z  dt          z  g=          }|                    t'          d>d?dVt          j        dG          fdWdCdDd?d@|fdEd?d@dFt          j        dG          fdXdadbd@t          j        |gfg                     (                    |            |dcdd|	                    ded+                      |d
df|	                    dgd+                     (                    t!          d2d                     (                    t          dh'                     (                    t)          dIdFt          j        dG          J                     (                    t!          d2d                     |	                    dii           }|rdjdkg|	                    dld5          |	                    dmd5          gdnd+g|	                    dod5          d+gg}t#          |dpt          z  dpt          z  g=          }|                    t'          d>d?dVt          j        dG          fd>dqdrt          j        dG          fdWdsdCdDd?d@|fdEd?d@dFt          j        dG          fdXdtdug
                     (                    |            |ddv|	                    dwd+                      |dxdy|	                    dzd+                      |dd{|	                    d|d+                      |d}d~|	                    dd+                      |dd|	                    dod+                     |	                    dg           }|r(                    t!          d2d                     (                    t          d'                     (                    t)          dIdFt          j        dG          J                     (                    t!          d2d                     ddgg}|D ]A}|                    |	                    dd5          |	                    d-d5          g           Bt#          |d
t          z  dt          z  g=          } |                     t'          d>d?dVt          j        dG          fdWdCdDd?d@|fdEd?d@dFt          j        dG          fdXdadbd@t          j        |gfg                     (                    |            |r(                    t!          d2d                     (                    t          d'                     (                    t)          dIdFt          j        dG          J                     (                    t!          d2d                     g dg}!|D ]D}"|"d-         dk    rdn|"d-         dk    rdnd}#|!                    |"d         |"d         |#g           Et#          |!dt          z  d
t          z  d;t          z  g=          }$|$                    t'          d>d?dVt          j        dG          fdWdCdDd?d@|fdEd?d@dFt          j        dG          fdHdadbd@t          j        |gfg                     (                    |$           (                    t!          d2d                     (                    t)          dId2t          j        dG          J                     (                    t!          d2d                     (                    t          d| 	                    dd           d| 	                    dd+           |
                     | 	                    dd+          }%|%r&(                    t          d|% &                     |                    (           |S )Ng      ?)pagesizerightMargin
leftMargin	topMarginbottomMarginz#1a1916z#7a7869z#f5f4f0TitleNormal   Helvetica-Bold      )parentfontSizefontName	textColor
spaceAfterleadingSub
   r$   )rS   rT   rV   rW   H1         )rS   rT   rU   rV   spaceBeforerW   Body   )rS   rT   rV   rX   rW   Label   )rS   rT   rV   rU   rW   rX   report_metadatasectionscompliance_checklistseverityCriticalz-INVESTIGATION REPORT  <font color="#c0392b">[z SEVERITY]</font>zRef ID: ref_idzDEV-2024-00001z  |  revisionzRev 01confidentialCONFIDENTIAL zStatus: r1   zAudit Readyz  |  Generated: generated_datez%Y-%m-%d   zBatch IDbatch_idu   —Productproduct_namePlantplantSeverityg333333?g      @)	colWidths
BACKGROUNDr   r   rz   )FONTNAMErx   )r   rz   rP   )r{   )r$   r   )r$   rz   rP   )FONTSIZErx   ry   	   	TEXTCOLORGRID      ?#e2e0d8)PADDINGrx   ry   r^   100%width	thicknesscolorai_generated_summaryzAI Generated Summaryc           	                              t          dd                                          t          |  d|                                           t          ddt	          j        d                                                    t          dd                     |r2                     t          t          |                               d S d S )	Nro   rZ   z. r   r   r   r   r^   )appendr   r   r   r	   HexColorr   )numbertitler(   
body_styleh1_stylestorys      r   add_sectionz!generate_pdf.<locals>.add_section$  s    VAr]]###Y&33E33X>>???Zf6?S\C]C]^^^___VAq\\""" 	>LL3w<<<<=====	> 	>r!   incident_overviewz01. Incident Overview)zBATCH NUMBERzINCIDENT DATEzDEVIATION TYPE
DEPARTMENTbatch_numberincident_datedeviation_type
departmentg      ?rz   r   )r{   rx   r   rP   )r   rx   ry   ra   detected_deviationsz02. Detected Deviations)zSIGNAL/EXCEPTIONDURATIONz
PEAK VALUELIMITsignal_exceptionduration
peak_valuelimitg      ?ROWBACKGROUNDS)r   ro      zExecutive Summaryexecutive_summaryzDeviation Descriptiondeviation_descriptionz05. Root Cause Analysisroot_cause_analysiszPROBABLE CAUSEMETHODOLOGYprobable_causemethodology
CONCLUSION
conclusiong      @r   r$   rz   r$   )r{   r   r   rP   )SPANr   )ro   r$   )r   )r   r   )ro   r   zScope of Reviewscope_of_review   
Exceptionsexceptions_summaryCAPAcapa_summaryr}   zImpact Assessmentimpact_assessment
Conclusionregulatory_compliancez11. Regulatory ComplianceStandardStatusstandardg	@zCompliance Checklist)r   Descriptionr   passu   ✓ Passwarnu
   ⚠ Reviewu   ✗ FaildescriptionzEvidence Coverage Score: evidence_coverage_scorer   u   % — confidence_label
ai_insightzAI Insight: )REPORTS_DIRr
   r   r   r   r   r	   r   r   getupperr   r   r   nowstrftimer   r   setStyler   r   whitebuild))rE   rF   filepathdocstylesdarkmutedlight_bgtitle_style	sub_stylelabel_stylemetare   	checklistrg   
batch_databatch_table
ai_summaryr   incinc_data	inc_tabledevsdev_datad	dev_tablercarca_data	rca_tablereg_compliancereg_datar	reg_table
check_dataitemstatus_textcheck_tabler   r   r   r   s)                                         @@@r   generate_pdfr      s   X%H
H4K$;+D[  C !""FE?9%%DOI&&Ey))H 1A.$b" " "K uVH-=u4 4 4Id6(+;.$1& & &H  vh/?tRA? ? ?J 1Ae.>b" " "K ::',,Dzz*b))H

1266Ixx
J//5577H 
LLSSSS     
LL 	X488H&677  	X  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XYYY	LL1	LLxFJJ/H!$L$LxxTZT^T^_qsuTvTvxx     L"--J IY:j::JGGHHHIIeOr!   r   c                 .  K   t          |            d {V }|                    di                               dd          }t          j                                        d          }d| d| d}t          ||           ||d<   | d	| |d
<   d|d<   |S )Nrd   rp   BATCHz%Y%m%d_%H%M%SInvestigation_Report__z.pdfpdf_filenamez/reports/download/download_url	completedr1   )rD   r   r   r   r   r   )r"   r   report_jsonrp   	timestamprF   s         r   generate_full_reportr     s      ,T22222222K0"5599*gNNH''88IAxAA)AAAHh'''"*K%-"K"K"K"KK'Kr!   )&osr2   pathlibr   openair   reportlab.lib.pagesizesr   reportlab.lib.stylesr   r   reportlab.lib.unitsr   reportlab.libr	   reportlab.platypusr
   r   r   r   r   r   r   fastapir   dotenvr   getenvr6   r   mkdirr4   r   r    dictrD   r   r    r!   r   <module>r     s   				              & & & & & & D D D D D D D D $ $ $ $ $ $             b b b b b b b b b b b b b b b b                   T    			"233	4	4	4d9oo   4       Vr-' -c - - - -"4T "4d "4 "4 "4 "4Jj j j j j j jZ	T 	S 	T 	 	 	 	 	 	r!   