// Production-safe debug logging utility
// Integrates with Cursor Debug Mode and backend debug-log API

window.DEBUG_LOG = async function(message, meta = {}, level = "info") {
    try {
        // Always log to console for clarity
        const levelPrefix = level === "error" ? "❌" : level === "warn" ? "⚠️" : "ℹ️";
        console.log(`[DEBUG] ${levelPrefix}`, message, meta);

        const hostname = window.location.hostname;
        const isLocal =
            hostname === "localhost" ||
            hostname === "127.0.0.1" ||
            hostname.endsWith(".local");

        const isCursorDebug = !!window.__CURSOR_DEBUG_MODE__;

        // Prepare log payload
        const logPayload = {
            timestamp: Date.now(),
            source: "frontend",
            level: level,
            message: message,
            meta: meta
        };

        // In production (non-local):
        // DISABLED: Debug logging to API is causing CORS/502 errors
        // Debug logs are only shown in console, not sent to backend
        if (!isLocal) {
            // Don't send to API - just log to console
            return;
        }

        // In development (local):
        // Only send to localhost debug endpoint if available
        // Don't send to production API even in debug mode to avoid CORS issues
        if (isCursorDebug) {
            // Only use localhost endpoint, not production API
            // (localhost endpoint code is below)
        }

        // Optional: Attempt localhost debug endpoint only in dev mode.
        // Must fail silently if not running.
        try {
            fetch("http://localhost:7777/debug-log", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(logPayload)
            }).catch(() => {
                // Fail silently — never surface errors.
            });
        } catch (err) {
            // Fail silently — localhost endpoint is optional.
        }

    } catch (err) {
        // Never throw - log utility must never break the app
        console.warn("DEBUG_LOG error:", err);
    }
};

// Convenience methods for different log levels
window.DEBUG_LOG.info = (message, meta) => window.DEBUG_LOG(message, meta, "info");
window.DEBUG_LOG.warn = (message, meta) => window.DEBUG_LOG(message, meta, "warn");
window.DEBUG_LOG.error = (message, meta) => window.DEBUG_LOG(message, meta, "error");
