import dspy
import json
import os
from datetime import datetime

def log_dspy_history_to_file() -> None:
    log_dir = "ai_payloads"
    """
    Logs only the output of dspy.inspect_history(n=1) to a timestamped JSON file.
    """
    os.makedirs(log_dir, exist_ok=True)

    timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    filename = os.path.join(log_dir, f"dspy_history_{timestamp}.json")

    # Capture the DSPy history by redirecting stdout
    from io import StringIO
    import sys
    
    # Create a string buffer to capture the output
    old_stdout = sys.stdout
    sys.stdout = history_capture = StringIO()

    # Inspect the last interaction
    dspy.inspect_history(n=1)
    
    # Restore stdout
    sys.stdout = old_stdout
    
    # Get the captured history and clean it up
    dspy_history = history_capture.getvalue().strip()

    log_data = {
        "dspy_history": dspy_history
    }

    try:
        with open(filename, "w", encoding="utf-8") as f:
            json.dump(log_data, f, indent=4)
        print(f"[LOG] DSPy history saved to {filename}")
    except IOError as e:
        print(f"[ERROR] Failed to write log file {filename}: {e}")