import { PluginRegistry, WebSocketPayload, LiveStatusData } from './types';
import LiveStatusPost from './components/live_status_post';
import './styles/live_status.css';

const PLUGIN_ID = 'com.openclaw.livestatus';
const WS_EVENT = `custom_${PLUGIN_ID}_update`;

class LiveStatusPlugin {
  private postTypeComponentId: string | null = null;

  initialize(registry: PluginRegistry, store: any): void {
    // Register custom post type renderer
    this.postTypeComponentId = registry.registerPostTypeComponent(
      'custom_livestatus',
      LiveStatusPost,
    );

    // Register WebSocket event handler
    registry.registerWebSocketEventHandler(WS_EVENT, (msg: any) => {
      const data = msg.data as WebSocketPayload;
      if (!data || !data.post_id) return;

      // Update global store
      const update: LiveStatusData = {
        session_key: data.session_key,
        post_id: data.post_id,
        agent_id: data.agent_id,
        status: data.status as LiveStatusData['status'],
        lines: data.lines || [],
        elapsed_ms: data.elapsed_ms || 0,
        token_count: data.token_count || 0,
        children: data.children || [],
        start_time_ms: data.start_time_ms || 0,
      };

      window.__livestatus_updates[data.post_id] = update;

      // Notify listeners
      const listeners = window.__livestatus_listeners[data.post_id];
      if (listeners) {
        listeners.forEach((fn) => fn(update));
      }
    });
  }

  uninitialize(): void {
    // Cleanup handled by Mattermost plugin framework
  }
}

// Initialize global stores
if (typeof window !== 'undefined') {
  window.__livestatus_updates = window.__livestatus_updates || {};
  window.__livestatus_listeners = window.__livestatus_listeners || {};
}

(window as any).registerPlugin(PLUGIN_ID, new LiveStatusPlugin());
