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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
/**
 * Brain-5D Operator Console — ES Module
 *
 * This module is a pure ES module. It does NOT self-initialize and does NOT
 * register any DOMContentLoaded listeners. The sole lifecycle owner is
 * `app.js`, which imports and instantiates `OperatorConsole` exactly once when
 * the Console tab is first activated.
 *
 * Canonical command contract (unified with ControlPanel):
 *   POST /api/control  { "command": "run_ticks", "ticks": 100 }
 *
 * No CommonJS fallbacks. No `module.exports`. No global side effects on import.
 *
 * @version 2.1.0
 * @license MIT
 */

"use strict";

import { readJson } from "./api-client.js";

import { StructuralProposalPanel } from './structural-proposal-panel.js';

// ============================================================================
// DOM Helpers
// ============================================================================

/**
 * Get element by ID with type safety.
 * @param {string} id - Element ID
 * @returns {HTMLElement | null}
 */
function byId(id) {
  return document.getElementById(id);
}

/**
 * Get element by ID or throw.
 * @param {string} id - Element ID
 * @param {string} context - Context for error message
 * @returns {HTMLElement}
 * @throws {Error} If element not found
 */
function requireElement(id, context = 'console') {
  const el = byId(id);
  if (!el) {
    throw new Error(`Required element "#${id}" not found in ${context}`);
  }
  return el;
}

/**
 * Set text content safely.
 * @param {string} id - Element ID
 * @param {string} text - Text to set
 */
function setText(id, text) {
  const el = byId(id);
  if (el) el.textContent = String(text);
}

/**
 * Set HTML content safely.
 * @param {string} id - Element ID
 * @param {string} html - HTML content
 */
function setHTML(id, html) {
  const el = byId(id);
  if (el) el.innerHTML = html;
}

// ============================================================================
// Utilities
// ============================================================================

/**
 * Format a timestamp.
 * @param {Date} date - Date object
 * @returns {string} Formatted time
 */
function formatTime(date = new Date()) {
  return date.toLocaleTimeString('en-US', { hour12: false });
}

/**
 * Escape HTML to prevent XSS.
 * @param {string} str - String to escape
 * @returns {string} Escaped string
 */
function escapeHtml(str) {
  if (!str) return '';
  const div = document.createElement('div');
  div.textContent = str;
  return div.innerHTML;
}

/**
 * Debounce a function.
 * @param {Function} fn - Function to debounce
 * @param {number} delay - Delay in milliseconds
 * @returns {Function} Debounced function
 */
function debounce(fn, delay) {
  let timer = null;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}

// ============================================================================
// API Client
// ============================================================================

export class OperatorAPI {
  /**
   * Fetch JSON from the dashboard API.
   * @param {string} url - API endpoint
   * @param {object} options - Fetch options
   * @returns {Promise<object>} JSON response
   * @throws {Error} On HTTP error or invalid response
   */
  static async fetchJSON(url, options = {}) {
    const response = await fetch(url, {
      ...options,
      headers: {
        'Cache-Control': 'no-store',
        ...(options.headers || {}),
      },
    });

    let data;
    try {
      data = await readJson(response);
    } catch {
      throw new Error(`Invalid JSON response from ${url}`);
    }

    if (!response.ok) {
      const message = data.error || data.message || `HTTP ${response.status}`;
      throw new Error(message);
    }

    return data;
  }

  /**
   * Send a control command.
   * @param {string} command - Command name
   * @param {object} params - Command parameters
   * @returns {Promise<object>} Command result
   */
  static async sendCommand(command, params = {}) {
    const body = { command, ...params };
    return this.fetchJSON('/api/control', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(body),
    });
  }

  /**
   * Get system status.
   * @returns {Promise<object>} Status data
   */
  static async getStatus() {
    return this.fetchJSON('/api/status');
  }

  /**
   * Get structural proposals.
   * @returns {Promise<object>} Proposals data
   */
  static async getProposals() {
    return this.fetchJSON('/api/structural/proposals');
  }

  /**
   * Approve a structural proposal.
   * @param {string} proposalId - Proposal ID
   * @returns {Promise<object>} Result
   */
  static async approveProposal(proposalId) {
    return this.fetchJSON('/api/structural/approve', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ proposal_id: proposalId }),
    });
  }

  /**
   * Reject a structural proposal.
   * @param {string} proposalId - Proposal ID
   * @returns {Promise<object>} Result
   */
  static async rejectProposal(proposalId) {
    return this.fetchJSON('/api/structural/reject', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ proposal_id: proposalId }),
    });
  }

  /**
   * Undo the last structural change.
   * @returns {Promise<object>} Result
   */
  static async undoStructural() {
    return this.fetchJSON('/api/structural/undo', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
    });
  }

  /**
   * Set auto-approval mode.
   * @param {boolean} enabled - Whether to enable
   * @returns {Promise<object>} Result
   */
  static async setAutoApproval(enabled) {
    return this.fetchJSON('/api/structural/auto-approval', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ enabled }),
    });
  }

  /**
   * Run ticks.
   * @param {number} count - Number of ticks
   * @returns {Promise<object>} Result
   */
  static async runTicks(count) {
    return this.sendCommand('run_ticks', { ticks: count });
  }

  /**
   * Single step.
   * @returns {Promise<object>} Result
   */
  static async step() {
    return this.sendCommand('step');
  }

  /**
   * Start the runtime.
   * @returns {Promise<object>} Result
   */
  static async start() {
    return this.sendCommand('start');
  }

  /**
   * Pause the runtime.
   * @returns {Promise<object>} Result
   */
  static async pause() {
    return this.sendCommand('pause');
  }

  /**
   * Resume the runtime.
   * @returns {Promise<object>} Result
   */
  static async resume() {
    return this.sendCommand('resume');
  }

  /**
   * Stop the runtime.
   * @returns {Promise<object>} Result
   */
  static async stop() {
    return this.sendCommand('stop');
  }

  /**
   * Request a snapshot.
   * @returns {Promise<object>} Result
   */
  static async snapshot() {
    return this.sendCommand('snapshot');
  }
}

// ============================================================================
// Console Logger (delegates to shared console-log.js)
// ============================================================================

export class ConsoleLogger {
  constructor(containerId) {
    this.container = byId(containerId);
    this.entries = [];
    this.maxEntries = 1000;
    this.sharedLog = null;
  }

  /**
   * Bind to the shared console log singleton.
   */
  async bindSharedLog() {
    if (this.sharedLog) return;
    try {
      const { consoleLog } = await import('./console-log.js');
      this.sharedLog = consoleLog;
    } catch {
      // Shared log unavailable; fall back to local rendering.
    }
  }

  /**
   * Log a message to the console.
   * @param {string} message - Message to log
   * @param {string} type - Log type ('info', 'success', 'error', 'warning')
   */
  log(message, type = 'info') {
    const entry = {
      timestamp: new Date(),
      message: String(message),
      type: type,
    };

    this.entries.push(entry);
    if (this.entries.length > this.maxEntries) {
      this.entries.shift();
    }

    if (this.sharedLog) {
      this.sharedLog.log(entry.message, entry.type);
    } else {
      this.render(entry);
    }
  }

  /**
   * Render a single log entry.
   * @param {object} entry - Log entry
   */
  render(entry) {
    if (!this.container) return;

    const time = formatTime(entry.timestamp);
    const classes = `log-entry log-${entry.type}`;

    const div = document.createElement('div');
    div.className = classes;
    div.innerHTML = `<span class="log-time">[${time}]</span> ${escapeHtml(entry.message)}`;

    this.container.appendChild(div);

    // Auto-scroll
    this.container.scrollTop = this.container.scrollHeight;

    // Limit DOM entries
    while (this.container.children.length > this.maxEntries) {
      this.container.removeChild(this.container.firstChild);
    }
  }

  /**
   * Clear the console.
   */
  clear() {
    if (this.container) {
      this.container.innerHTML = '';
    }
    this.entries = [];
  }

  /**
   * Get all log entries.
   * @returns {Array} Log entries
   */
  getEntries() {
    return [...this.entries];
  }
}

// ============================================================================
// Operator Console
// ============================================================================

export class OperatorConsole {
  constructor() {
    this.logger = null;
    this.pollingInterval = null;
    this.pollingRate = 1000;
    this.status = null;
    this.proposalPanel = null;

    // Bind methods
    this.handleCommand = this.handleCommand.bind(this);
    this.refreshStatus = this.refreshStatus.bind(this);
    this.init();
  }

  /**
   * Initialize the console.
   */
  init() {
    // Initialize logger and bind to shared console log
    this.logger = new ConsoleLogger('console-output');
    this.logger.bindSharedLog().then(() => {
      this.logger.log('🧠 Brain-5D Operator Console initialized', 'info');
      this.logger.log(`📡 API endpoint: /api/control`, 'info');
      this.proposalPanel = new StructuralProposalPanel({
        api: OperatorAPI,
        logger: this.logger,
        onChanged: this.refreshStatus,
      });
      this.proposalPanel.load();
    });

    // Bind event listeners
    this.bindEvents();
    this.bindKeyboardShortcuts();

    // Initial load
    this.refreshStatus();
    // Start polling
    this.startPolling();
  }

  /**
   * Bind DOM event listeners.
   */
  bindEvents() {
    // Runtime controls and structural proposals are owned by their panels.

    // Clear console
    const clearBtn = byId('b5d-clear-console');
    if (clearBtn) {
      clearBtn.addEventListener('click', () => this.logger.clear());
    }

  }

  /**
   * Bind keyboard shortcuts.
   */
  bindKeyboardShortcuts() {
    document.addEventListener('keydown', (e) => {
      // Ctrl+L = Clear console (if focus is on console)
      if (e.ctrlKey && e.key === 'l' && document.activeElement?.id === 'console-output') {
        e.preventDefault();
        this.logger.clear();
      }
    });
  }

  /**
   * Handle a command.
   * @deprecated Runtime commands are now owned by ControlPanel.
   */
  async handleCommand(action, params = {}) {
    this.logger.log(`ℹ️ Runtime commands moved to Runtime Control panel (${action})`, 'info');
  }

  /**
   * Handle undo structural change.
   * @deprecated Structural undo is now owned by ControlPanel.
   */
  async handleUndo() {
    this.logger.log('ℹ️ Structural undo moved to Runtime Control panel', 'info');
  }

  /**
   * Refresh system status.
   */
  async refreshStatus() {
    try {
      const data = await OperatorAPI.getStatus();
      this.status = data;
      this.renderStatus(data);
    } catch (error) {
      this.logger.log(`⚠️ Failed to refresh status: ${error.message}`, 'warning');
    }
  }

  /**
   * Render system status.
   * @param {object} data - Status data
   */
  renderStatus(data) {
    // Update status badge
    const badge = byId('b5d-state-badge');
    if (badge) {
      const state = data.state || 'idle';
      badge.textContent = state;
      badge.className = `status-badge status-${state}`;
    }

    // Update tick count
    const tickEl = byId('b5d-tick-display');
    if (tickEl) {
      tickEl.textContent = String(data.tick || 0);
    }

    // Update metrics
    const metrics = byId('b5d-metrics');
    if (metrics && data.system) {
      const s = data.system;
      metrics.innerHTML = `
        <span>🧠 ${(s.neurons || 0).toLocaleString()}</span>
        <span>🔗 ${(s.synapses || 0).toLocaleString()}</span>
        <span>⚡ ${(s.spikes_total || 0).toLocaleString()}</span>
      `;
    }
  }

  /**
   * Start polling for status updates.
   */
  startPolling() {
    if (this.pollingInterval) {
      clearInterval(this.pollingInterval);
    }

    this.pollingInterval = setInterval(() => {
      this.refreshStatus().catch(() => {});
    }, this.pollingRate);
  }

  /**
   * Stop polling.
   */
  stopPolling() {
    if (this.pollingInterval) {
      clearInterval(this.pollingInterval);
      this.pollingInterval = null;
    }
  }

  /**
   * Set polling rate.
   * @param {number} ms - Milliseconds
   */
  setPollingRate(ms) {
    if (ms < 100) ms = 100;
    this.pollingRate = ms;
    if (this.pollingInterval) {
      this.startPolling();
    }
  }

  /**
   * Destroy the console instance.
   */
  destroy() {
    this.stopPolling();
    this.logger.log('🛑 Operator Console shutting down', 'info');
  }
}