import json
from typing import List, Dict, Any

class DatasetBuilder:
    def format_for_finetuning(self, events: List[Dict[str, Any]]) -> str:
        """
        Converts a list of conversational events into JSONL format for fine-tuning.
        
        Expected input format:
        [
            {"role": "user", "content": "Hello"},
            {"role": "assistant", "content": "Hi there!"}
        ]
        
        Output format (JSONL string):
        {"prompt": "Hello", "completion": "Hi there!"}\n
        """
        jsonl_lines = []
        
        current_prompt = None
        
        for event in events:
            role = event.get("role")
            content = event.get("content", "")
            
            if role == "user":
                current_prompt = content
            elif role == "assistant":
                if current_prompt is not None:
                    # Construct matching pair
                    line = json.dumps({"prompt": current_prompt, "completion": content})
                    jsonl_lines.append(line)
                    # Reset after matching pair
                    current_prompt = None
                    
        if not jsonl_lines:
            return ""
            
        return "\n".join(jsonl_lines) + "\n"
