import * as vscode from 'vscode';
import { PROVIDER_SPECS, providerLabel } from '@lib/providers';
import { hasApiKey, readSettings } from './config';

export type LexAIStatus = 'ready' | 'processing' | 'notReady';

let item: vscode.StatusBarItem | undefined;
let contextRef: vscode.ExtensionContext | undefined;
let busyDepth = 0;
let lastStatus: LexAIStatus = 'notReady';

export function registerStatusBar(context: vscode.ExtensionContext): void {
  contextRef = context;
  item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
  item.name = 'LexAI';
  item.command = 'lexai.openSettings';
  item.show();
  context.subscriptions.push(item);

  context.subscriptions.push(
    context.secrets.onDidChange((e) => {
      if (e.key === 'lexai.apiKey') void refreshStatusBar();
    }),
    vscode.workspace.onDidChangeConfiguration((e) => {
      if (e.affectsConfiguration('lexai')) void refreshStatusBar();
    }),
  );

  void refreshStatusBar();
}

export async function refreshStatusBar(): Promise<void> {
  if (!item || !contextRef) return;
  if (busyDepth > 0) {
    apply('processing');
    return;
  }
  const keyed = await hasApiKey(contextRef);
  apply(keyed ? 'ready' : 'notReady');
}

/** Nestable busy indicator for generate / regenerate. */
export async function withLexAIProgress<T>(title: string, task: () => Promise<T>): Promise<T> {
  busyDepth += 1;
  apply('processing', title);
  try {
    return await vscode.window.withProgress(
      {
        location: vscode.ProgressLocation.Window,
        title,
      },
      async () => task(),
    );
  } finally {
    busyDepth = Math.max(0, busyDepth - 1);
    await refreshStatusBar();
  }
}

function apply(status: LexAIStatus, detail?: string): void {
  if (!item) return;
  lastStatus = status;
  const settings = readSettings();
  const provider = providerLabel(settings.provider);
  const model = settings.model || PROVIDER_SPECS[settings.provider]?.defaultModel || 'default';

  switch (status) {
    case 'ready':
      item.text = '$(check) LexAI';
      item.backgroundColor = undefined;
      item.tooltip = `LexAI ready · ${provider} · ${model}\nClick to open settings`;
      break;
    case 'processing':
      item.text = '$(sync~spin) LexAI';
      item.backgroundColor = new vscode.ThemeColor('statusBarItem.warningBackground');
      item.tooltip = detail ? `LexAI: ${detail}` : 'LexAI is working…';
      break;
    case 'notReady':
      item.text = '$(warning) LexAI';
      item.backgroundColor = new vscode.ThemeColor('statusBarItem.errorBackground');
      item.tooltip = 'LexAI not ready — click to set your API key';
      break;
  }
}

export function getLexAIStatus(): LexAIStatus {
  return lastStatus;
}
