"""Save CAMEL workflow execution results to text files.

This module provides functionality to save conversation results from CAMEL
role-playing workflows to formatted text files for review and analysis.
"""

from datetime import datetime
from pathlib import Path
from typing import Dict, Any, Optional


def save_conversation_result(
    user_task: str,
    result: Dict[str, Any],
    output_dir: Optional[Path] = None,
) -> Path:
    """Save conversation results to a text file.
    
    Args:
        user_task: Original task description from user.
        result: Conversation result dictionary containing conversation history,
                role information, and completion status.
        output_dir: Output directory path. If None, uses default outputs directory.
    
    Returns:
        Path to the saved output file.
    """
    if output_dir is None:
        current_file = Path(__file__)
        output_dir = current_file.parent / "outputs"
    
    output_dir.mkdir(exist_ok=True)
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    output_file = output_dir / f"camel_conversation_{timestamp}.txt"
    conversation_result = result.get("conversation_result", {})
    assistant_role = conversation_result.get("assistant_role_name", "Unknown")
    user_role = conversation_result.get("user_role_name", "Unknown")
    final_task = conversation_result.get("task", user_task)
    task_completed = conversation_result.get("task_completed", False)
    conversation_history = conversation_result.get("conversation_history", [])
    final_user_msg = conversation_result.get("final_user_message", "")
    final_assistant_msg = conversation_result.get("final_assistant_message", "")
    
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write("=" * 80 + "\n")
        f.write("CAMEL Role-Playing Workflow\n")
        f.write("=" * 80 + "\n")
        f.write(f"Original Task: {user_task}\n")
        f.write("=" * 80 + "\n")
        f.write("\nStarting workflow execution...\n")
        f.write("(Role names will be automatically generated by LLM)\n\n")
        
        f.write("\n" + "=" * 80 + "\n")
        f.write("Workflow Execution Completed!\n")
        f.write("=" * 80 + "\n")
        f.write(f"\nAuto-generated Roles:\n")
        f.write(f"  AI Assistant: {assistant_role}\n")
        f.write(f"  AI User: {user_role}\n")
        f.write(f"\nSpecified Task: {final_task}\n")
        f.write("\nConversation Results:\n")
        f.write(f"Task Completed: {task_completed}\n")
        if conversation_history:
            f.write("\n" + "=" * 80 + "\n")
            f.write("Complete Conversation History:\n")
            f.write("=" * 80 + "\n")
            
            grouped_history = []
            current_turn = {}
            for msg in conversation_history:
                if msg['role'] == 'AI User':
                    if current_turn:
                        grouped_history.append(current_turn)
                    current_turn = {'user_message': msg['content'], 'assistant_message': ''}
                elif msg['role'] == 'AI Assistant':
                    current_turn['assistant_message'] = msg['content']
                    grouped_history.append(current_turn)
                    current_turn = {}
            if current_turn:
                grouped_history.append(current_turn)

            for i, turn in enumerate(grouped_history, 1):
                f.write(f"\n[Turn {i}]\n")
                f.write("=" * 80 + "\n")
                f.write(f"AI User:\n")
                f.write("-" * 80 + "\n")
                f.write(turn.get('user_message', '') + "\n\n")
                f.write(f"AI Assistant:\n")
                f.write("-" * 80 + "\n")
                f.write(turn.get('assistant_message', '') + "\n")
        else:
            f.write("\nNo conversation history found\n")
            if final_user_msg:
                f.write(f"\nFinal User Message: {final_user_msg}\n")
            if final_assistant_msg:
                f.write(f"\nFinal Assistant Message: {final_assistant_msg}\n")
    
    # Output file path is returned, caller can print if needed
    return output_file

