"""Session command for managing agent sessions"""

from .base import BuiltinCommand
from diona.project.agent import get_session_manager


class SessionCommand(BuiltinCommand):
    """Session command for managing agent sessions"""
    name = "session"
    description = "Manage agent sessions"
    
    def execute(self, args):
        """Execute session command
        
        Args:
            args: Command arguments
                - list: List all sessions
                - create [name]: Create a new session
                - switch <id>: Switch to a session
                - delete <id>: Delete a session
                - current: Show current session
        """
        if not args:
            self._print_help()
            return False
        
        session_mgr = get_session_manager()
        action = args[0]
        
        if action == "list":
            sessions = session_mgr.list_sessions()
            if not sessions:
                print("No sessions found")
                return False
            
            current_id = session_mgr.get_current_session_id()
            print("Available sessions:")
            for session in sessions:
                marker = " *" if session.session_id == current_id else ""
                print(f"  {session.session_id[:8]} - {session.name} (last active: {session.last_active.strftime('%Y-%m-%d %H:%M:%S')}){marker}")
        
        elif action == "create":
            name = args[1] if len(args) > 1 else None
            session_id = session_mgr.create_session(name)
            print(f"Created new session: {session_id[:8]}")
        
        elif action == "switch":
            if len(args) < 2:
                print("Usage: /session switch <session_id>")
                return False
            
            session_id_prefix = args[1]
            
            sessions = session_mgr.list_sessions()
            matched = None
            for s in sessions:
                if s.session_id.startswith(session_id_prefix):
                    matched = s
                    break
                elif s.name == session_id_prefix:
                    matched = s
                    break
            
            if matched:
                session_mgr.set_current_session(matched.session_id)
                print(f"Switched to session: {matched.session_id[:8]} - {matched.name}")
            else:
                print(f"Session not found: {session_id_prefix}")
        
        elif action == "delete":
            if len(args) < 2:
                print("Usage: /session delete <session_id>")
                return False
            
            session_id_prefix = args[1]
            
            sessions = session_mgr.list_sessions()
            matched = None
            for s in sessions:
                if s.session_id.startswith(session_id_prefix):
                    matched = s
                    break
                elif s.name == session_id_prefix:
                    matched = s
                    break
            
            if matched:
                session_mgr.delete_session(matched.session_id)
                print(f"Deleted session: {matched.session_id[:8]} - {matched.name}")
            else:
                print(f"Session not found: {session_id_prefix}")
        
        elif action == "current":
            current_id = session_mgr.get_current_session_id()
            if current_id:
                session = session_mgr.get_session(current_id)
                if session:
                    print(f"Current session: {session.session_id[:8]} - {session.name}")
                    print(f"Created: {session.created_at.strftime('%Y-%m-%d %H:%M:%S')}")
                    print(f"Last active: {session.last_active.strftime('%Y-%m-%d %H:%M:%S')}")
                else:
                    print("No current session")
            else:
                print("No current session")
        
        else:
            self._print_help()
        
        return False
    
    def _print_help(self):
        """Print help message"""
        print("Usage: /session <action> [arguments]")
        print("Actions:")
        print("  list              - List all sessions")
        print("  create [name]     - Create a new session")
        print("  switch <id>       - Switch to a session")
        print("  delete <id>       - Delete a session")
        print("  current           - Show current session")


session_command = SessionCommand()
