"""
sessions.py — List and manage chat sessions.
"""
import os
from datetime import datetime
from rich.console import Console
from rich.table import Table

from onefirewall_ai.config import SESSIONS_DIR

console = Console()

def list_sessions() -> None:
    """List all available session IDs and their last user message."""
    if not SESSIONS_DIR.exists():
        console.print("No sessions found (directory missing).")
        return

    files = list(SESSIONS_DIR.glob("*.md"))
    if not files:
        console.print("No sessions found.")
        return

    table = Table(title="Recent Sessions")
    table.add_column("Session ID", style="cyan")
    table.add_column("Last Updated", style="magenta")
    table.add_column("Last Message", style="green")

    # Sort by modification time, descending
    files.sort(key=lambda x: os.path.getmtime(x), reverse=True)

    for f in files[:15]:  # limit to 15 to avoid huge tables
        session_id = f.stem
        mtime = os.path.getmtime(f)
        last_updated = datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M:%S")

        try:
            text = f.read_text(encoding="utf-8")
        except Exception:
            text = ""

        last_msg = ""
        for line in reversed(text.splitlines()):
            if line.startswith("**User:** "):
                last_msg = line[len("**User:** "):].strip()
                if len(last_msg) > 50:
                    last_msg = last_msg[:47] + "..."
                break

        table.add_row(session_id, last_updated, last_msg)

    console.print(table)
