/**
 * DSS Logger - Component Brain Consciousness System
 *
 * The DSS brain uses this logger to become conscious of what's happening.
 * Log levels represent the component's level of awareness and concern.
 *
 * Framework: DSS Component Framework
 * See: docs/DSS_ORGANISM_GUIDE.md#brain
 *
 * Log Categories (Organ Systems):
 *   'heart'         - ❤️ Database operations and data persistence
 *   'brain'         - 🧠 Validation, analysis, and decision making
 *   'nervous'       - 🔌 API calls, webhooks, communication
 *   'digestive'     - 🍽️ Data ingestion, parsing, transformation
 *   'circulatory'   - 🩸 Design token flow and distribution
 *   'metabolic'     - ⚡ Style-dictionary transformations
 *   'endocrine'     - 🎛️ Theme system and configuration
 *   'immune'        - 🛡️ Validation, error detection, security
 *   'sensory'       - 👁️ Asset loading, Figma perception
 *   'skin'          - 🎨 UI rendering, Storybook output
 *   'skeleton'      - 🦴 Schema and structure validation
 *
 * Provides structured logging with biological awareness levels and optional remote logging.
 */

// Component awareness levels - how conscious is the system?
const LOG_LEVELS = {
  DEBUG: 0,    // 🧠 Deep thought - brain analyzing internal processes
  INFO: 1,     // 💭 Awareness - component knows what's happening
  WARN: 2,     // ⚠️ Symptom - component detected something unusual
  ERROR: 3,    // 🛡️ Immune alert - component detected a threat
  NONE: 4      // 🌙 Sleep - component is silent
};

class Logger {
  constructor(name = 'DSS', level = 'INFO') {
    this.name = name;
    this.level = LOG_LEVELS[level] || LOG_LEVELS.INFO;
    this.logs = [];
    this.maxLogs = 1000;
    this.remoteLoggingEnabled = false;
  }

  setLevel(level) {
    this.level = LOG_LEVELS[level] || LOG_LEVELS.INFO;
  }

  enableRemoteLogging() {
    this.remoteLoggingEnabled = true;
  }

  _shouldLog(level) {
    return LOG_LEVELS[level] >= this.level;
  }

  _formatMessage(level, category, message, data) {
    const timestamp = new Date().toISOString();
    return {
      timestamp,
      level,
      category,
      name: this.name,
      message,
      data
    };
  }

  _log(level, category, message, data = null) {
    if (!this._shouldLog(level)) return;

    const logEntry = this._formatMessage(level, category, message, data);

    // Store in memory
    this.logs.push(logEntry);
    if (this.logs.length > this.maxLogs) {
      this.logs.shift();
    }

    // Console output with component awareness emojis
    const levelEmojis = {
      DEBUG: '🧠',      // Brain thinking deeply
      INFO: '💭',       // Component aware
      WARN: '⚠️',       // Symptom detected
      ERROR: '🛡️'      // Immune alert - threat detected
    };

    const colors = {
      DEBUG: 'color: #666; font-style: italic',  // Gray, thoughtful
      INFO: 'color: #2196F3; font-weight: bold',  // Blue, informative
      WARN: 'color: #FF9800; font-weight: bold',  // Orange, warning
      ERROR: 'color: #F44336; font-weight: bold'  // Red, critical
    };

    const emoji = levelEmojis[level] || '🔘';
    const prefix = `${emoji} [${category}]`;
    const style = colors[level] || '';

    if (data) {
      console.log(`%c${prefix} ${message}`, style, data);
    } else {
      console.log(`%c${prefix} ${message}`, style);
    }

    // Remote logging (if enabled)
    if (this.remoteLoggingEnabled && level === 'ERROR') {
      this._sendToServer(logEntry);
    }
  }

  async _sendToServer(logEntry) {
    try {
      await fetch('/api/logs', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(logEntry)
      });
    } catch (e) {
      // Fail silently for logging errors
    }
  }

  /**
   * 🧠 DEBUG - Brain's deep thoughts
   * Internal analysis and detailed consciousness
   */
  debug(category, message, data) {
    this._log('DEBUG', category, message, data);
  }

  /**
   * 💭 INFO - Component awareness
   * The system knows what's happening, stays informed
   */
  info(category, message, data) {
    this._log('INFO', category, message, data);
  }

  /**
   * ⚠️ WARN - Symptom detection
   * Component detected something unusual but not critical
   */
  warn(category, message, data) {
    this._log('WARN', category, message, data);
  }

  /**
   * 🛡️ ERROR - Immune alert
   * Component detected a threat - critical consciousness
   */
  error(category, message, data) {
    this._log('ERROR', category, message, data);
  }

  /**
   * 📜 Get recent consciousness records
   * Retrieve the component's recent thoughts and awareness
   */
  getRecentLogs(count = 50) {
    return this.logs.slice(-count);
  }

  /**
   * 🧠 Clear the mind
   * Erase recent consciousness logs
   */
  clear() {
    this.logs = [];
  }

  /**
   * 📤 Export consciousness
   * Save the component's awareness to a file for analysis
   */
  export() {
    const dataStr = JSON.stringify(this.logs, null, 2);
    const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr);

    const exportFileDefaultName = `dss-logs-${Date.now()}.json`;

    const linkElement = document.createElement('a');
    linkElement.setAttribute('href', dataUri);
    linkElement.setAttribute('download', exportFileDefaultName);
    linkElement.click();
  }
}

/**
 * 🧠 ORGANISM CONSCIOUSNESS
 * Create the DSS component's brain - a singleton logger that tracks all awareness
 */
const logger = new Logger('DSS', 'INFO');

// Set log level from localStorage or URL param
// Allow tuning the component's consciousness level (awareness sensitivity)
const urlParams = new URLSearchParams(window.location.search);
const logLevel = urlParams.get('log') || localStorage.getItem('dss_log_level') || 'INFO';
logger.setLevel(logLevel.toUpperCase());

export default logger;
export { Logger, LOG_LEVELS };
