import type { Command } from 'commander';
import type { SessionStore } from '../session/index.js';
import { getDataDir } from './shared.js';
import { resolve } from 'path';

export interface SessionInfo {
  id: string;
  messageCount: number;
}

/** List all sessions with their message counts. */
export function listSessions(store: SessionStore): SessionInfo[] {
  const sessionIds = store.listSessions();
  return sessionIds.map((id) => ({
    id,
    messageCount: store.getMessages(id).length,
  }));
}

export function registerSessionsCommand(program: Command): void {
  program
    .command('sessions')
    .description('List active sessions')
    .action(async () => {
      const dataDir = getDataDir();
      const dbPath = resolve(dataDir, 'sessions.db');

      const { SessionStore: Store } = await import('../session/index.js');
      const store = new Store(dbPath);

      try {
        const sessions = listSessions(store);

        if (sessions.length === 0) {
          console.log('No sessions found.');
          return;
        }

        console.log('Sessions:');
        console.log('');
        for (const session of sessions) {
          console.log(`  ${session.id}  (${session.messageCount} messages)`);
        }
        console.log('');
        console.log(`Total: ${sessions.length} session(s)`);
      } finally {
        store.close();
      }
    });
}
