"""
Session logs tool for the AGS SPARQL Agent.

This tool retrieves session information, log files, and recent interaction summaries.
"""

import os
import sys
import re

# Add src directory to path for imports
src_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
if src_dir not in sys.path:
    sys.path.insert(0, src_dir)

from ..base_tool import BaseToolMixin, handle_tool_errors, ToolError


@handle_tool_errors
async def get_session_logs() -> str:
    """Get the latest interaction logs and session summary.
    
    This tool retrieves session information, log files, and recent interaction
    summaries for debugging and monitoring purposes.
    
    Returns:
        JSON response with session logs and interaction history
    """
    try:
        from interaction_logger import get_logger
        
        logger = get_logger()
        
        # Get session summary
        summary = logger.get_session_summary()
        
        # List available log files
        log_files = logger.list_log_files()
        
        # Read the latest interaction logs (last 5 interactions)
        recent_interactions = []
        if logger.interactions_file.exists():
            # For markdown files, we'll read the file and extract interaction summaries
            with open(logger.interactions_file, 'r', encoding='utf-8') as f:
                content = f.read()
                
                # Extract interaction headers for summary
                interaction_matches = re.findall(r'# Interaction (\S+)\n\*\*Timestamp:\*\* ([^\n]+)\n\*\*Execution Time:\*\* ([^\n]+)\n\*\*Confidence:\*\* ([^\n]+)', content)
                
                for match in interaction_matches[-5:]:  # Last 5 interactions
                    interaction_id, timestamp, exec_time, confidence = match
                    recent_interactions.append({
                        "interaction_id": interaction_id,
                        "timestamp": timestamp,
                        "execution_time": exec_time,
                        "confidence": confidence
                    })
        
        return BaseToolMixin.create_success_response({
            "session_summary": summary,
            "log_files": log_files,
            "recent_interactions": recent_interactions,
            "logs_directory": str(logger.log_dir),
            "log_format": "markdown",
            "interactions_file": str(logger.interactions_file)
        })
        
    except Exception as e:
        return BaseToolMixin.create_error_response(
            str(e),
            details={
                "session_summary": {},
                "log_files": [],
                "recent_interactions": []
            }
        )