from datetime import datetime
from pathlib import Path

from libtmux import Server, Session
from tomlkit import comment, document, nl, table
from tomlkit.items import AoT

from tmurkser.config_file import get_config_dir


class SessionSaver:
    """Class to save tmux sessions."""

    save_file: Path
    server: Server

    def __init__(self, save_file: str):
        """Initialize the SessionSaver with a save file path."""
        self.save_file = get_config_dir() / f"{save_file}.toml"
        self.server = Server()

    def save_sessions(
        self,
        all: bool = False,
        session_names: list[str] | None = None,
        exclude_names: list[str] | None = None,
    ):
        """Save the current tmux sessions.

        Args:
            all (bool): If True, save all sessions.
            session_names (list[str]): List of session names to save.
            exclude_names (list[str]): List of session names to exclude from saving.
        """

        sessions: list[Session]

        if all:
            sessions = self.server.sessions
        elif session_names:
            sessions = self.server.sessions.filter(name__in=session_names)
        elif exclude_names:
            excluded_ids = [
                s.id for s in self.server.sessions.filter(name__in=exclude_names)
            ]
            sessions = [s for s in self.server.sessions if s.id not in excluded_ids]
        else:
            print("No session names provided.")
            raise

        self._write_sessions_to_file(sessions)

    def _write_sessions_to_file(self, sessions: list[Session]):
        """Write the sessions to the save file."""
        doc = document()
        doc.add(comment("Tmux session save file generated by tmurkser"))
        doc.add(comment(f"Generated on: {datetime.now().isoformat()}"))
        doc.add(nl())

        session_list = AoT([])

        for session in sessions:
            session_object = table()
            session_object.add("name", session.name)

            windows = AoT([])
            for window in session.windows:
                path = ""
                if window.active_pane:
                    cmd = window.active_pane.cmd(
                        "display-message", "-p", "#{pane_current_path}"
                    )
                    if cmd.returncode == 0:
                        path = cmd.stdout[0].strip()

                if not path:
                    print("Failed to get the working path, defaulting to empty string")

                window_object = table()
                window_object.add("name", window.name)
                window_object.add("path", path)
                windows.append(window_object)
            session_object.add("windows", windows)
            session_list.append(session_object)

        doc.add("sessions", session_list)

        with open(self.save_file, "w") as f:
            f.write(doc.as_string())
            f.write("\n")
