import { useQuery } from '@tanstack/react-query';
import { useClient } from 'hooks/useClient';
import { useAuth } from 'hooks/useAuth';

/**
 * A session the agent has a process behind RIGHT NOW.
 *
 * Not the same question as `useClaudeSessions`, which lists conversations from transcripts on disk.
 * Those are history and outnumber these enormously; this is the handful that are actually alive.
 */
export type LiveSession = {
  sessionKey: string;
  /**
   * Claude's own id, which is what `/chat/:sessionId` opens — distinct from `sessionKey`, officer's
   * handle for the same conversation. Null before the first turn has reported one.
   */
  claudeSessionId: string | null;
  isGenerating: boolean;
  /** Background tasks started but not yet notified — `run_in_background`, Monitor, and friends. */
  pendingTasks: number;
  /**
   * Resolved server-side, and null when no transcript has been written yet.
   *
   * It has to come from there: the agent reports keys, and a client can only name the sessions in the
   * group it is currently browsing — so anything running in another directory showed a raw id.
   */
  title: string | null;
  cwd: string | null;
};

const LIVE_KEY = 'CHAT_LIVE_SESSIONS';

/**
 * Polled rather than pushed. Liveness is owned by the agent sidecar and changes without officer being
 * told — a turn ends, a background task reports — so there is no event to subscribe to that covers
 * every transition. Ten seconds is short enough that the list is never meaningfully wrong and long
 * enough to be free; the request is one in-memory map read on the other side.
 *
 * `refetchIntervalInBackground` is deliberately left off: a hidden tab does not need to know.
 */
export function useLiveSessions() {
  const client = useClient();
  const { isAuthenticated } = useAuth();

  const { data, isLoading, error, refetch } = useQuery<{ sessions: LiveSession[] }>({
    queryKey: [LIVE_KEY],
    queryFn: () => client.get<{ sessions: LiveSession[] }>('/chat/live'),
    enabled: isAuthenticated,
    refetchInterval: 10_000,
    staleTime: 5_000,
  });

  return {
    live: data?.sessions ?? [],
    isLoading,
    error,
    refetch,
  };
}
