import requests
import json
import io
from cerebras.cloud.sdk import Cerebras
from settings import CEREBRAS_API_KEY, CEREBRAS_MODEL, DISCORD_WEBHOOK_URL, OPENAI_IN_COST, OPENAI_OUT_COST

class CerebrasReportingLayer:
    def __init__(self):
        self.client = Cerebras(api_key=CEREBRAS_API_KEY)

    def process_and_notify(self, audit_result, openai_usage, patient_name):
        # حساب التكلفة بناءً على أسعار OpenAI في config.py
        in_cost = openai_usage.prompt_tokens * OPENAI_IN_COST
        out_cost = openai_usage.completion_tokens * OPENAI_OUT_COST
        total_cost = in_cost + out_cost
        
        summary_prompt = f"Summarize this medical audit for a Discord notification: {json.dumps(audit_result)}"
        cer_res = self.client.chat.completions.create(
            model=CEREBRAS_MODEL,
            messages=[{"role": "user", "content": summary_prompt}]
        )

        payload = {
            "embeds": [{
                "title": f"OpenAI Medical Audit: {patient_name}",
                "description": cer_res.choices[0].message.content,
                "color": 3447003, # لون أزرق لـ OpenAI
                "fields": [
                    {"name": "Success Rate", "value": audit_result.get('success_rate'), "inline": False},
                    {
                        "name": "Token Usage (GPT-4o)",
                        "value": f"**Prompt:** {openai_usage.prompt_tokens}\n**Total:** {openai_usage.total_tokens}",
                        "inline": True
                    },
                    {
                        "name": "Estimated Cost",
                        "value": f"${total_cost:.6f}", 
                        "inline": True
                    }
                ]
            }]
        }

        # إرسال الملف والـ Embed لديسكورد
        json_file = io.BytesIO(json.dumps(audit_result, indent=4).encode('utf-8'))
        requests.post(
            DISCORD_WEBHOOK_URL,
            data={"payload_json": json.dumps(payload)},
            files={"file": (f"{patient_name}_audit.json", json_file)}
        )