# ===========================================================
#  live_mode_example.py
#  Clean text + OpenAI client (compatible with your VRS app)
# ===========================================================

import os
from openai import OpenAI
from dotenv import load_dotenv   # <-- REQUIRED IMPORT

# Load secrets
load_dotenv("/etc/pixcura-secrets.env")

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")

# Initialize OpenAI client
client = OpenAI(api_key=OPENAI_API_KEY)

# ---------- 2) Clean transcript based on specialty ----------
def clean_live_text(raw_transcript: str, specialty="radiology", language="en"):
    """
    Cleans raw transcript text according to the chosen specialty.
    You can extend this later for multiple specialties.
    """

    # Basic safety
    if not raw_transcript or not isinstance(raw_transcript, str):
        return ""

    # Build a cleaning instruction
    system_prompt = f"""
You are a medical language model specializing in {specialty}.
Your task is to clean and correct spoken dictation.

Rules:
- Fix grammar and punctuation.
- Fix accent/pronunciation mistakes.
- Keep ONLY English.
- Do NOT add findings.
- Do NOT remove clinical meaning.
- Make the output clean, professional, and concise.
"""

    try:
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": raw_transcript},
            ],
            temperature=0.1,
        )

        cleaned_text = response.choices[0].message["content"]
        return cleaned_text.strip()

    except Exception as e:
        print("Error in clean_live_text:", e)
        return raw_transcript  # fallback
