/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 *
 * Geometry Diagnostics Module
 * Lightweight instrumentation used during ruler / layout refinement.
 * Safe to leave in production; does nothing unless console.debug available.
 */
export function logGeometryDiagnostics(editor, context='manual') {
  try {
    // Debug gating: only emit detailed logs when debug flag or explicit geom flag is set
    const debugFlag = (typeof localStorage !== 'undefined' && (localStorage.getItem('ccveDebugUI') === '1' || localStorage.getItem('ccveGeom') === '1'))
      || (document?.body?.dataset?.ccveDebug === '1');
    // Lightweight suppression: if not debug, only record internal buffer (no console output)
    const allowConsole = !!debugFlag;
    // Simple debounce: collapse rapid successive calls within 50ms when console logging enabled
    const now = Date.now();
    if (allowConsole) {
      if (!editor.__geomLastTs) { editor.__geomLastTs = 0; }
      if (now - editor.__geomLastTs < 50) {
        // Skip console emission (still update buffer below)
        editor.__geomSuppressed = (editor.__geomSuppressed||0)+1;
        // Continue to collect metrics but bail before heavy work after scale computation
      }
      editor.__geomLastTs = now;
    }
    const targetW = 960, targetH = 540;
    const wrap = document.querySelector('#block-stage-wrapper');
    const stageOuter = wrap?.querySelector('.ccve-stage-outer');
    const stage = stageOuter?.querySelector('.canvas-stage');
    const grid = wrap?.querySelector('.ccve-stage-grid');
    const hRuler = wrap?.querySelector('.ccve-ruler-horizontal');
    const vRuler = wrap?.querySelector('.ccve-ruler-vertical');
    const blockWrap = wrap?.querySelector('.cc-block-editor-wrap');
    const r = el => {
      if (!el) return null;
      const b = el.getBoundingClientRect();
      return { x: Math.round(b.left), y: Math.round(b.top), width: Math.round(b.width), height: Math.round(b.height) };
    };
    const scale = (function(){
      try { if (editor?.getPreviewScale) return editor.getPreviewScale(); } catch(_) {}
      // Fallback: infer from canvas-stage width vs 1920
      if (stage) {
        const w = stage.getBoundingClientRect().width;
        if (w) return +(w / 1920).toFixed(4);
      }
      return 1;
    })();
    const stageRect = r(stageOuter) || r(stage) || null;
    const deltas = stageRect ? {
      width: stageRect.width - targetW,
      height: stageRect.height - targetH,
      x: stageRect.x,
      y: stageRect.y
    } : null;
    const payload = {
      context,
      scaleFactor: scale,
      target: { width: targetW, height: targetH },
      stageRect,
      gridRect: r(grid),
      blockWrapRect: r(blockWrap),
      hRulerRect: r(hRuler),
      vRulerRect: r(vRuler),
      deltas,
      ts: Date.now()
    };
    // Maintain rolling buffer
    if (editor) {
      if (!Array.isArray(editor._geomLogs)) editor._geomLogs = [];
      editor._geomLogs.push(payload);
      if (editor._geomLogs.length > 60) editor._geomLogs.shift();
    }
    if (allowConsole) {
      if (editor.__geomSuppressed) {
        payload.suppressed = editor.__geomSuppressed;
        editor.__geomSuppressed = 0;
      }
      if (Math.abs((deltas?.width)||0) > 1 || Math.abs((deltas?.height)||0) > 1) {
        console.debug('[CCVE][geom][Δ]', payload);
      } else {
        console.debug('[CCVE][geom]', payload);
      }
    }
  } catch(e) {
    try { console.warn('[CCVE] geometry diagnostics failed', e); } catch(_) {}
  }
}

export function attachGeometryDiagnostics(editor) {
  editor.logGeometryDiagnostics = (ctx) => logGeometryDiagnostics(editor, ctx);
}
