"""
Session Controller

Controller for session management operations.

v2.0: Includes pagination support for large session lists.
"""

from honeydb_ai.domain.models import Session, SessionMetadata
from honeydb_ai.infrastructure.ui.console import RichConsoleUI
from honeydb_ai.services.session_service import SessionService
from honeydb_ai.utils.formatters import (
    format_datetime,
    format_message_count,
    format_relative_time,
    format_session_title,
    format_size_bytes,
)
from honeydb_ai.utils.logging import get_logger


class SessionController:
    """
    Controller for session management.

    v2.0: Supports pagination for large session lists.
    """

    def __init__(self, session_service: SessionService, console: RichConsoleUI):
        """
        Initialize session controller.

        Args:
            session_service: Session service instance
            console: Console UI instance
        """
        self.session_service = session_service
        self.console = console
        self.logger = get_logger()

    def create_session(self, title: str = "New Session") -> Session:
        """
        Create a new session.

        Args:
            title: Session title

        Returns:
            New Session object
        """
        session = self.session_service.create_session(title)
        # Session info will be displayed by chat controller
        return session

    def save_session(self, session: Session) -> None:
        """
        Save a session.

        Args:
            session: Session to save
        """
        try:
            self.session_service.save_session(session)
            self.console.print_success(f"Session saved: {session.id}")
        except Exception as e:
            self.console.print_error(f"Failed to save session: {e}")
            raise

    def load_session(self, session_id: str) -> Session:
        """
        Load a session.

        Args:
            session_id: Session ID to load

        Returns:
            Loaded Session object
        """
        try:
            session = self.session_service.load_session(session_id)
            self.console.print_success(f"Session loaded: {session.id}")
            return session
        except Exception as e:
            self.console.print_error(f"Failed to load session: {e}")
            raise

    def delete_session(self, session_id: str, confirm: bool = True) -> None:
        """
        Delete a session.

        Args:
            session_id: Session ID to delete
            confirm: Whether to ask for confirmation
        """
        if confirm:
            confirmed = self.console.confirm(
                f"Are you sure you want to delete session {session_id}?",
                default=False
            )
            if not confirmed:
                self.console.print("Deletion cancelled.", style="dim")
                return

        try:
            self.session_service.delete_session(session_id)
            self.console.print_success(f"Session deleted: {session_id}")
        except Exception as e:
            self.console.print_error(f"Failed to delete session: {e}")
            raise

    def list_sessions(
        self,
        limit: int | None = None,
        offset: int = 0,
        show_details: bool = False
    ) -> list[SessionMetadata]:
        """
        List all sessions.

        v2.0 Major Enhancement #6: Pagination support.

        Args:
            limit: Maximum number of sessions to display (None for all)
            offset: Number of sessions to skip
            show_details: Whether to show detailed information

        Returns:
            List of session metadata
        """
        sessions = self.session_service.list_sessions()

        if not sessions:
            self.console.print("No sessions found.", style="dim")
            return []

        # Apply pagination
        total = len(sessions)
        if offset > 0:
            sessions = sessions[offset:]
        if limit:
            sessions = sessions[:limit]

        # Display header
        self.console.print(f"Sessions ({len(sessions)} of {total} total):", style="info")
        self.console.print_divider()

        # Display sessions
        for i, metadata in enumerate(sessions, start=offset + 1):
            self._display_session_metadata(metadata, index=i, show_details=show_details)

        # Display pagination info
        if limit and total > offset + len(sessions):
            remaining = total - offset - len(sessions)
            self.console.print(
                f"\n{remaining} more session(s) available. Use --offset {offset + len(sessions)} to see more.",
                style="dim"
            )

        return sessions

    def _display_session_metadata(
        self,
        metadata: SessionMetadata,
        index: int | None = None,
        show_details: bool = False
    ) -> None:
        """
        Display a single session's metadata.

        Args:
            metadata: Session metadata
            index: Optional index number
            show_details: Whether to show detailed information
        """
        # Build display string
        prefix = f"{index}. " if index else ""
        title = format_session_title(metadata.title, max_length=50)

        # Basic info
        self.console.print(f"{prefix}[bold]{title}[/bold]", style="info")
        self.console.print(f"  ID: {metadata.id}", style="dim")
        self.console.print(f"  Messages: {format_message_count(metadata.message_count)}", style="dim")
        self.console.print(f"  Updated: {format_relative_time(metadata.updated_at)}", style="dim")

        # Detailed info
        if show_details:
            self.console.print(f"  Size: {format_size_bytes(metadata.size_bytes)}", style="dim")
            self.console.print(f"  Created: {format_datetime(metadata.created_at)}", style="dim")

        self.console.print("")  # Empty line between sessions

    def display_session(self, session: Session, show_messages: bool = False) -> None:
        """
        Display session details.

        Args:
            session: Session to display
            show_messages: Whether to show message history
        """
        metadata = self.session_service.get_session_metadata(session)

        self.console.print_panel(
            f"ID: {session.id}\n"
            f"Title: {session.title}\n"
            f"Messages: {format_message_count(len(session.messages))}\n"
            f"Size: {format_size_bytes(session.get_size_bytes())}\n"
            f"Created: {format_datetime(session.created_at)}\n"
            f"Updated: {format_datetime(session.updated_at)}",
            title="Session Details",
            style="info"
        )

        if show_messages and session.messages:
            self.console.print("\nMessage History:", style="info")
            self.console.print_divider()

            for msg in session.messages:
                role_style = "user" if msg.role == "user" else "assistant"
                self.console.print(f"\n[{role_style}]{msg.role.upper()}[/{role_style}]")

                if msg.role == "assistant":
                    self.console.print_markdown(msg.content)
                else:
                    self.console.print(msg.content)

                self.console.print_divider()

    def export_session(self, session: Session, output_path: str, format: str = "json") -> None:
        """
        Export session to a file.

        Args:
            session: Session to export
            output_path: Output file path
            format: Export format (json, markdown, text)
        """
        from pathlib import Path

        output = Path(output_path).expanduser().resolve()

        try:
            if format == "json":
                # Export as JSON (Pydantic v2: field_serializer handles datetime)
                output.write_text(session.model_dump_json(indent=2), encoding='utf-8')

            elif format == "markdown":
                # Export as Markdown
                lines = [
                    f"# {session.title}\n",
                    f"**Session ID:** {session.id}\n",
                    f"**Created:** {format_datetime(session.created_at)}\n",
                    f"**Updated:** {format_datetime(session.updated_at)}\n",
                    f"**Messages:** {len(session.messages)}\n",
                    "\n---\n\n",
                ]

                for msg in session.messages:
                    lines.append(f"## {msg.role.upper()}\n")
                    lines.append(f"{msg.content}\n\n")

                output.write_text("".join(lines), encoding='utf-8')

            elif format == "text":
                # Export as plain text
                lines = [
                    f"Session: {session.title}\n",
                    f"ID: {session.id}\n",
                    f"Created: {format_datetime(session.created_at)}\n",
                    f"Updated: {format_datetime(session.updated_at)}\n",
                    f"Messages: {len(session.messages)}\n",
                    "\n" + "=" * 80 + "\n\n",
                ]

                for msg in session.messages:
                    lines.append(f"{msg.role.upper()}:\n")
                    lines.append(f"{msg.content}\n")
                    lines.append("\n" + "-" * 80 + "\n\n")

                output.write_text("".join(lines), encoding='utf-8')

            else:
                raise ValueError(f"Unsupported export format: {format}")

            self.console.print_success(f"Session exported to: {output}")

        except Exception as e:
            self.console.print_error(f"Failed to export session: {e}")
            raise
