#!/bin/bash
#
# GET_BROWSER_LOGS.sh - Hook to capture browser logs from DSS dashboard
#
# Usage:
#   ./GET_BROWSER_LOGS.sh
#
# This script provides instructions for capturing browser logs when debugging DSS
#

cat << 'EOF'
╔══════════════════════════════════════════════════════════════╗
║           DSS Browser Log Capture - Quick Hook              ║
╚══════════════════════════════════════════════════════════════╝

STEP 1: Open DSS Dashboard
  → https://dss.overbits.luz.uy/
  → Or: http://localhost:3456/admin-ui/index.html

STEP 2: Open Browser DevTools
  → Chrome/Edge: F12 or Cmd+Option+I (Mac) or Ctrl+Shift+I (Windows)
  → Firefox: F12 or Cmd+Option+K (Mac) or Ctrl+Shift+K (Windows)
  → Go to "Console" tab

STEP 3: Run Commands in Console

  📊 Get System Diagnostic:
  ──────────────────────────
  window.__DSS_BROWSER_LOGS.diagnostic()

  ❌ Get All Errors:
  ──────────────────────────
  window.__DSS_BROWSER_LOGS.errors()

  🌐 Get Network Activity:
  ──────────────────────────
  window.__DSS_BROWSER_LOGS.network()

  📋 Get All Logs:
  ──────────────────────────
  window.__DSS_BROWSER_LOGS.all()

  💾 Export Everything as JSON:
  ──────────────────────────
  JSON.stringify(window.__DSS_BROWSER_LOGS.export(), null, 2)

  📄 Download Logs to File:
  ──────────────────────────
  const data = window.__DSS_BROWSER_LOGS.export();
  const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'dss-browser-logs-' + Date.now() + '.json';
  a.click();

STEP 4: Analyze Results

  The diagnostic will show:
  ✓ Session ID
  ✓ Uptime
  ✓ Total logs captured
  ✓ Error count
  ✓ Warning count
  ✓ Network request count
  ✓ Memory usage
  ✓ Recent errors (last 5)
  ✓ Recent network requests (last 5)

STEP 5: Advanced Filtering

  Search for specific issues:
  ──────────────────────────
  window.__DSS_BROWSER_LOGGER.getLogs({
    search: 'config',    // Search term
    level: 'error',      // Filter by level
    category: 'fetch',   // Filter by category
    limit: 50            // Max results
  })

  Get logs from time range:
  ──────────────────────────
  const oneHourAgo = Date.now() - (60 * 60 * 1000);
  window.__DSS_BROWSER_LOGGER.getLogs({
    minTime: oneHourAgo,
    limit: 100
  })

TROUBLESHOOTING
───────────────────────────────────────────────────────────────

If window.__DSS_BROWSER_LOGS is undefined:

  1. Check browser-logger.js is loaded:
     → Check Network tab for /admin-ui/js/core/browser-logger.js
     → Should see 200 OK response

  2. Manually load it:
     → import('/admin-ui/js/core/browser-logger.js').then(() => {
         console.log('Logger loaded:', window.__DSS_BROWSER_LOGS);
       })

  3. Check for JavaScript errors:
     → Look for red errors in Console tab
     → Fix any module loading issues

WHAT'S CAPTURED AUTOMATICALLY
───────────────────────────────────────────────────────────────

✓ All console.log/warn/error/info/debug calls
✓ Uncaught JavaScript errors
✓ Unhandled promise rejections
✓ Network requests (fetch API)
✓ Performance metrics (page load time, etc.)
✓ Memory usage warnings (if >80%)
✓ Long tasks (>50ms execution time)

DATA STRUCTURE
───────────────────────────────────────────────────────────────

Each log entry contains:
{
  timestamp: 1733456789000,        // Unix timestamp
  relativeTime: 1234,              // Ms since session start
  level: 'log|warn|error|info',   // Log level
  category: 'console|fetch|...',  // Category
  message: 'Description',          // Human-readable message
  data: { ... },                   // Additional context
  url: 'https://...',              // Page URL
  userAgent: 'Mozilla/...'         // Browser info
}

INTEGRATION STATUS
───────────────────────────────────────────────────────────────

✅ browser-logger.js created
⏳ Need to import in index.html or app.js
⏳ Need to test in browser
⏳ API endpoint not yet created (optional)

RELATED TOOLS
───────────────────────────────────────────────────────────────

Server-side debugging:
  → window.__DSS_DEBUG.printDiagnosis()
  → See .dss/DSS_SELF_DEBUG_METHODOLOGY.md

Full documentation:
  → .dss/BROWSER_LOG_CAPTURE_PROCEDURE.md
  → .dss/DEBUG_QUICKSTART.md

EOF

echo ""
echo "📖 Full documentation: .dss/BROWSER_LOG_CAPTURE_PROCEDURE.md"
echo "🔧 Browser logger module: admin-ui/js/core/browser-logger.js"
echo ""
echo "Next step: Import browser-logger.js in admin-ui/index.html or app.js"
