import json
from openai import OpenAI  # استبدال Groq
from prompt_manager import PromptManager
from settings import OPENAI_API_KEY, OPENAI_MODEL

class VascularConsultantAgent:
    def __init__(self, api_key):
        self.client = OpenAI(api_key=api_key)
        self.model_decision = OPENAI_MODEL
        self.compressor = PromptManager()
        
    def generate_final_audit(self, visual_summary, patient_json):
        from notifier import CerebrasReportingLayer
        
        notes = patient_json.get('Operative Note', 'No notes provided')
        patient_name = patient_json.get('name', 'Unknown')

        # ضغط النصوص لتقليل التكلفة
        c_notes = self.compressor.compress_input(notes, max_tokens=500)

        user_prompt = f"""
        Act as a senior vascular surgery consultant. Rely on your own clinical judgment by integrating the surgical notes and the visual evidence provided.
        
        [EVIDENCE - SURGICAL NOTES]: {c_notes}
        [EVIDENCE - IMAGING ANALYSIS]: {visual_summary}

        Answer strictly in JSON format:
        {{
          "procedure_Notes": "Was the procedure appropriate? Explain technical relevance.",
          "procedure_result": "Must be start Yes or No, Is it successful based on flow/imaging? Include specific visual findings.",
          "success_rate": "XX% + clinical justification"
        }}
        """

        response = self.client.chat.completions.create(
            model=self.model_decision,
            messages=[{"role": "user", "content": user_prompt}],
            response_format={"type": "json_object"},
            temperature=0.0
        )
        
        final_content = json.loads(response.choices[0].message.content)
        usage = response.usage

        try:
            reporting = CerebrasReportingLayer()
            reporting.process_and_notify(final_content, usage, patient_name)
        except Exception as e:
            print(f"Notification Error: {e}")
        
        return final_content
