import express from 'express';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const router = express.Router();

// Configure telemetry log file path
const LOG_DIR = '/home/overbits/dss-monitor/logs/console';
const LOG_FILE = path.join(LOG_DIR, 'browser_errors.log');

// Ensure log directory exists
if (!fs.existsSync(LOG_DIR)) {
  fs.mkdirSync(LOG_DIR, { recursive: true, mode: 0o755 });
}

// Rate limiting state (simple in-memory implementation)
const rateLimitMap = new Map();
const RATE_LIMIT_WINDOW = 60 * 1000; // 1 minute
const MAX_REQUESTS_PER_WINDOW = 100;

/**
 * Simple rate limiting middleware
 */
function rateLimit(req, res, next) {
  const clientIP = req.ip || req.connection.remoteAddress;
  const now = Date.now();

  if (!rateLimitMap.has(clientIP)) {
    rateLimitMap.set(clientIP, { count: 1, resetTime: now + RATE_LIMIT_WINDOW });
    return next();
  }

  const clientData = rateLimitMap.get(clientIP);

  if (now > clientData.resetTime) {
    // Reset window
    rateLimitMap.set(clientIP, { count: 1, resetTime: now + RATE_LIMIT_WINDOW });
    return next();
  }

  if (clientData.count >= MAX_REQUESTS_PER_WINDOW) {
    return res.status(429).json({
      status: 'error',
      code: 'RATE_LIMIT_EXCEEDED',
      message: 'Too many telemetry requests. Please try again later.'
    });
  }

  clientData.count++;
  next();
}

/**
 * POST /api/telemetry/log
 * Receive browser telemetry and log to file
 */
router.post('/log', rateLimit, (req, res) => {
  try {
    const telemetryData = req.body;

    // Validate required fields
    if (!telemetryData.type || !telemetryData.level) {
      return res.status(400).json({
        status: 'error',
        code: 'INVALID_TELEMETRY',
        message: 'Missing required fields: type and level'
      });
    }

    // Format log entry
    const timestamp = telemetryData.timestamp || new Date().toISOString();
    const logEntry = {
      timestamp,
      type: telemetryData.type,
      level: telemetryData.level,
      message: telemetryData.message || '',
      url: telemetryData.url || '',
      userAgent: telemetryData.userAgent || '',
      filename: telemetryData.filename || '',
      lineno: telemetryData.lineno || '',
      colno: telemetryData.colno || '',
      stack: telemetryData.stack || ''
    };

    // Format as single-line JSON for easy parsing
    const logLine = JSON.stringify(logEntry) + '\\n';

    // Append to log file (async, non-blocking)
    fs.appendFile(LOG_FILE, logLine, (err) => {
      if (err) {
        console.error('[Telemetry] Failed to write to log file:', err);
      }
    });

    // Return success immediately (don't wait for file write)
    res.status(200).json({ status: 'ok' });

  } catch (error) {
    console.error('[Telemetry] Error processing telemetry:', error);
    res.status(500).json({
      status: 'error',
      code: 'TELEMETRY_ERROR',
      message: 'Failed to process telemetry data'
    });
  }
});

/**
 * GET /api/telemetry/status
 * Get telemetry system status
 */
router.get('/status', (req, res) => {
  try {
    const stats = fs.existsSync(LOG_FILE) ? fs.statSync(LOG_FILE) : null;

    res.status(200).json({
      status: 'success',
      data: {
        logFile: LOG_FILE,
        exists: !!stats,
        size: stats ? stats.size : 0,
        lastModified: stats ? stats.mtime : null,
        rateLimitActive: rateLimitMap.size > 0
      }
    });
  } catch (error) {
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
});

export default router;
