// Maps our live-turn sessionKey → OpenCode's own session id (`ses_…`), the analog of
// sidecar/claude/state.ts's sessionKey→claude-uuid map. In-memory only: OpenCode's SQLite store is
// the durable record, and a fresh key just creates a new OpenCode session.

const sessionKeyToOpenCode = new Map<string, string>();

export const getOpenCodeSession = (sessionKey: string): string | undefined => sessionKeyToOpenCode.get(sessionKey);

export const setOpenCodeSession = (sessionKey: string, opencodeSessionId: string): void => {
  sessionKeyToOpenCode.set(sessionKey, opencodeSessionId);
};

export const clearOpenCodeSession = (sessionKey: string): void => {
  sessionKeyToOpenCode.delete(sessionKey);
  sessionKeyToPrompt.delete(sessionKey);
};

// What the user asked, kept only to name a session OpenCode has not named yet.
//
// OpenCode titles a session from the conversation, and does it well — but asynchronously, so a RUNNING
// turn is called `New session - <ISO>`, which is precisely when `/chat/live` displays it. This is the
// stand-in for that window: shown while the real title is still the placeholder, and dropped the moment
// OpenCode publishes its own, which is always the better one.
//
// Set on the FIRST turn of a session only, so it stays the name of the conversation rather than
// following whatever was asked most recently.
const sessionKeyToPrompt = new Map<string, string>();

export const rememberOpenCodePrompt = (sessionKey: string, prompt: string): void => {
  if (sessionKeyToPrompt.has(sessionKey)) return;
  const oneLine = prompt.replace(/\s+/g, ' ').trim();
  if (!oneLine) return;
  sessionKeyToPrompt.set(sessionKey, oneLine.length > 60 ? `${oneLine.slice(0, 59)}…` : oneLine);
};

export const getOpenCodePrompt = (sessionKey: string): string | undefined => sessionKeyToPrompt.get(sessionKey);
