"""
Example implementation of live text cleaning for VRS (Voice Reporting System)

This demonstrates how to use the live mode prompts to clean partial transcripts
in real-time as the doctor speaks.
"""

import os
from pathlib import Path
from openai import OpenAI
from typing import Optional

# Initialize OpenAI client
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

# Get the root directory (parent of examples folder)
ROOT_DIR = Path(__file__).parent.parent

# Load prompts
def load_prompt(filepath: str) -> str:
    """Load a prompt template from file."""
    # If relative path, make it relative to root directory
    if not os.path.isabs(filepath):
        filepath = ROOT_DIR / filepath
    with open(filepath, 'r', encoding='utf-8') as f:
        return f.read()

LIVE_SYSTEM_PROMPT = load_prompt("prompts/live_system_prompt.txt")
LIVE_USER_TEMPLATE = load_prompt("prompts/live_user_template.txt")


def clean_live_text(
    raw_transcript: str,
    specialty: str = "radiology",
    language: str = "en",
    model: str = "gpt-4o-mini"  # Fast, low-latency model
) -> str:
    """
    Clean partial live transcript for on-screen preview.
    
    Args:
        raw_transcript: Raw speech-to-text output (may be incomplete)
        specialty: Medical specialty (e.g., "radiology", "cardiology")
        language: Language code (e.g., "en")
        model: OpenAI model to use (default: gpt-4o-mini for low latency)
    
    Returns:
        Cleaned text ready for display
    """
    # Build user prompt by replacing template variables
    user_prompt = LIVE_USER_TEMPLATE.replace("{{specialty}}", specialty)
    user_prompt = user_prompt.replace("{{language}}", language)
    user_prompt = user_prompt.replace("{{raw_live_transcript}}", raw_transcript)
    
    # Call OpenAI API
    response = client.chat.completions.create(
        model=model,
        messages=[
            {"role": "system", "content": LIVE_SYSTEM_PROMPT},
            {"role": "user", "content": user_prompt}
        ],
        temperature=0.1,  # Low temperature for consistent, minimal changes
        max_tokens=500,   # Keep responses short for speed
    )
    
    return response.choices[0].message.content.strip()


# Example usage in a real-time loop
def live_preview_loop():
    """
    Example of how to integrate this into a real-time ASR loop.
    
    In practice, you would:
    1. Receive partial transcripts from OpenAI Realtime API every 1-2 seconds
    2. Call clean_live_text() with the latest transcript
    3. Update the on-screen preview with the cleaned text
    4. When doctor clicks "Finish", switch to final report generation
    """
    
    # Simulated partial transcripts (in real app, these come from ASR)
    partial_transcripts = [
        "history colon chest pain technique ct chest with contrast",
        "history colon chest pain technique ct chest with contrast findings there is no focal consolidation",
        "history colon chest pain technique ct chest with contrast findings there is no focal consolidation no pleural effusion no pneumothorax heart size normal",
        "history colon chest pain technique ct chest with contrast findings there is no focal consolidation no pleural effusion no pneumothorax heart size normal impression no acute intrathoracic pathology"
    ]
    
    print("=== Live Preview Updates ===\n")
    
    for i, raw_text in enumerate(partial_transcripts, 1):
        print(f"Update {i}:")
        print(f"Raw: {raw_text}")
        
        cleaned = clean_live_text(
            raw_transcript=raw_text,
            specialty="radiology",
            language="en"
        )
        
        print(f"Cleaned: {cleaned}\n")


if __name__ == "__main__":
    # Example usage
    example_raw = "history colon chest pain technique ct chest with contrast findings there is no focal consolidation no pleural effusion no pneumothorax heart size normal impression no acute intrathoracic pathology"
    
    cleaned = clean_live_text(
        raw_transcript=example_raw,
        specialty="radiology",
        language="en"
    )
    
    print("Example:")
    print(f"Raw: {example_raw}")
    print(f"\nCleaned: {cleaned}")

