import * as vscode from 'vscode';
import { ACTIONS, ACTION_LABELS, type ActionId } from '@lib/actions';
import { PROVIDER_SPECS, providerLabel } from '@lib/providers';
import { clearApiKey, hasApiKey, readSettings } from './config';
import { runActionOnSelection } from './analyze';
import { registerCodeAssistUi, runCodeAssist } from './codeAssist';
import {
  refreshSelectionAffordance,
  registerSelectionAffordance,
} from './selectionAffordance';
import { registerSidebarView } from './sidebarView';
import { openSettingsPanel } from './settingsPanel';
import { refreshStatusBar, registerStatusBar } from './statusBar';
import { registerSuggestionZone } from './suggestionZone';

export function activate(context: vscode.ExtensionContext): void {
  registerStatusBar(context);
  registerSidebarView(context);
  registerSuggestionZone(context);
  registerCodeAssistUi(context);
  registerSelectionAffordance(context, async (action) => {
    if (action === 'codeAssist') {
      await runCodeAssist(context);
      return;
    }
    await runActionOnSelection(context, action);
  });

  // Extension Host sometimes mounts CodeLens after the first selection event;
  // nudge a refresh so the LexAI lens appears without opening Settings first.
  setTimeout(() => refreshSelectionAffordance(), 0);
  setTimeout(() => refreshSelectionAffordance(), 300);

  for (const action of ACTIONS) {
    context.subscriptions.push(
      vscode.commands.registerCommand(`lexai.${action}`, () =>
        runActionOnSelection(context, action as ActionId),
      ),
    );
  }

  context.subscriptions.push(
    vscode.commands.registerCommand('lexai.codeAssist', () => runCodeAssist(context)),
    vscode.commands.registerCommand('lexai.openSettings', async () => {
      openSettingsPanel(context);
      await refreshStatusBar();
    }),
    vscode.commands.registerCommand('lexai.setApiKey', async () => {
      openSettingsPanel(context);
      await refreshStatusBar();
    }),
    vscode.commands.registerCommand('lexai.clearApiKey', () => clearApiKeyCommand(context)),
    vscode.commands.registerCommand('lexai.showStatus', () => showStatusCommand(context)),
  );
}

export function deactivate(): void {
  // nothing to tear down
}

async function clearApiKeyCommand(context: vscode.ExtensionContext): Promise<void> {
  const confirm = await vscode.window.showWarningMessage(
    'Clear the stored LexAI API key from Secret Storage?',
    { modal: true },
    'Clear',
  );
  if (confirm !== 'Clear') return;
  await clearApiKey(context);
  await refreshStatusBar();
  void vscode.window.showInformationMessage('LexAI: API key cleared.');
}

async function showStatusCommand(context: vscode.ExtensionContext): Promise<void> {
  const settings = readSettings();
  const keyed = await hasApiKey(context);
  const spec = PROVIDER_SPECS[settings.provider];
  const model = settings.model || spec?.defaultModel || '(none)';
  const lines = [
    `Provider: ${providerLabel(settings.provider)} (${settings.provider})`,
    `Model: ${model}`,
    `Writing style: ${settings.writingStyle}`,
    `Prompt: ${settings.promptPattern} / ${settings.promptPersona} / ${settings.promptFormat}`,
    `API key: ${keyed ? 'set (Secret Storage)' : 'not set'}`,
    '',
    'Select code → LexAI → Code Assist for workspace-aware help.',
    'Writing actions: ' + ACTIONS.map((a) => ACTION_LABELS[a]).join(', '),
  ];
  void vscode.window.showInformationMessage(lines.join(' · '), { modal: true });
}
