import os
import json
from pathlib import Path
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv(override=True)
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

CAPA_PROMPT = """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>
"""


async def generate_capa(data: dict) -> dict:
    try:
        data_str = json.dumps(data, indent=2)
        prompt = CAPA_PROMPT.replace("<content>", data_str[:8000])

        response = client.chat.completions.create(
            model="gpt-4o",
            messages=[
                {
                    "role": "system",
                    "content": "You are a pharma CAPA planning engine. Return JSON only. No extra text."
                },
                {
                    "role": "user",
                    "content": prompt
                }
            ],
            response_format={"type": "json_object"},
            temperature=0
        )

        raw = response.choices[0].message.content
        result = json.loads(raw)
        result["status"] = "completed"
        return result

    except json.JSONDecodeError as e:
        return {
            "status": "parse_error",
            "error": str(e),
            "capa_actions": [],
            "impact_assessment": {},
            "effectiveness_tracking": {},
            "action_verification_status": [],
            "pre_closure_checklist": {
                "root_cause_verified_by_qa": False,
                "no_recurrence_in_monitoring_period": False,
                "equipment_re_qualified": False,
                "all_corrective_actions_closed": False,
                "regulatory_submission_ready": False,
                "training_records_updated": False
            },
            "plan_approval": {
                "status": "Pending",
                "approved_by": None,
                "approved_at": None,
                "send_for_execution": False
            }
        }
    except Exception as e:
        return {
            "status": "error",
            "error": str(e),
            "capa_actions": [],
            "impact_assessment": {},
            "effectiveness_tracking": {},
            "action_verification_status": [],
            "pre_closure_checklist": {
                "root_cause_verified_by_qa": False,
                "no_recurrence_in_monitoring_period": False,
                "equipment_re_qualified": False,
                "all_corrective_actions_closed": False,
                "regulatory_submission_ready": False,
                "training_records_updated": False
            },
            "plan_approval": {
                "status": "Pending",
                "approved_by": None,
                "approved_at": None,
                "send_for_execution": False
            }
        }