import type { ThemedToken } from 'shiki';

export interface HighlightRequest {
  id: string;
  filePath: string;
  language: string; // resolved lang name (e.g. "typescript") or "text"
  code: string; // full joined content of new-side lines to highlight
  lineNumbers: number[]; // new-side line numbers to map tokens back to
}

export interface HighlightResponse {
  id: string;
  tokens: Array<{ lineNumber: number; tokens: ThemedToken[] }>;
  error?: string;
}

self.addEventListener('message', async (event: MessageEvent<HighlightRequest>) => {
  const { id, language, code, lineNumbers } = event.data;
  try {
    const { codeToTokens } = await import('shiki');
    const result = await codeToTokens(code, {
      lang: language as Parameters<typeof codeToTokens>[1]['lang'],
      theme: 'github-dark-default',
    });
    const tokens: HighlightResponse['tokens'] = result.tokens.map((lineTokens, idx) => ({
      lineNumber: lineNumbers[idx] ?? idx,
      tokens: lineTokens,
    }));
    const response: HighlightResponse = { id, tokens };
    self.postMessage(response);
  } catch (err) {
    const response: HighlightResponse = {
      id,
      tokens: [],
      error: err instanceof Error ? err.message : String(err),
    };
    self.postMessage(response);
  }
});
