import * as vscode from "vscode";
import { BridgeClient } from "../bridge/client";

/**
 * Manages the status bar item showing bridge connection status.
 */
export class StatusBarManager {
  private _item: vscode.StatusBarItem;
  private _pollTimer: ReturnType<typeof setInterval> | undefined;
  private _connected = false;

  constructor(private readonly _client: BridgeClient) {
    this._item = vscode.window.createStatusBarItem(
      vscode.StatusBarAlignment.Left,
      50
    );
    this._item.command = "mcpGrid.openDashboard";
    this._item.name = "MCP Grid Status";
    this._update(false, 0);
    this._item.show();
  }

  /** Start polling for bridge status. */
  startPolling(intervalMs: number = 5000): void {
    this.stopPolling();
    this._poll(); // immediate first check
    this._pollTimer = setInterval(() => this._poll(), intervalMs);
  }

  /** Stop polling. */
  stopPolling(): void {
    if (this._pollTimer) {
      clearInterval(this._pollTimer);
      this._pollTimer = undefined;
    }
  }

  /** Force an immediate status update. */
  async forceUpdate(): Promise<void> {
    await this._poll();
  }

  get isConnected(): boolean {
    return this._connected;
  }

  dispose(): void {
    this.stopPolling();
    this._item.dispose();
  }

  private async _poll(): Promise<void> {
    try {
      const status = await this._client.getStatus();
      this._connected = true;
      this._update(true, status.active_instances);
    } catch {
      this._connected = false;
      this._update(false, 0);
    }
  }

  private _update(connected: boolean, activeInstances: number): void {
    if (connected) {
      this._item.text = `$(check) MCP Grid: ${activeInstances} instance${activeInstances !== 1 ? "s" : ""}`;
      this._item.backgroundColor = undefined;
      this._item.tooltip = `MCP Grid bridge connected. ${activeInstances} active instance(s). Click to open dashboard.`;
    } else {
      this._item.text = "$(circle-slash) MCP Grid: Offline";
      this._item.backgroundColor = new vscode.ThemeColor(
        "statusBarItem.warningBackground"
      );
      this._item.tooltip =
        "MCP Grid bridge is not running. Click to open dashboard.";
    }
  }
}
