using System;
using System.Collections.Generic;
using System.IO;
using System.Web;

namespace CNCSystem.Core.Helpers
{
    public class Logger
    {
        private static readonly object _lock = new object();
        
        public static void LogInfo(string message, string category = "General")
        {
            Log("INFO", message, category);
        }

        public static void LogWarning(string message, string category = "General")
        {
            Log("WARNING", message, category);
        }

        public static void LogError(string message, string category = "General")
        {
            Log("ERROR", message, category);
        }

        public static void LogDebug(string message, string category = "General")
        {
            Log("DEBUG", message, category);
        }

        public static void Log(string level, string message, string category = "General", Exception exception = null)
        {
            try
            {
                lock (_lock)
                {
                    var logDirectory = HttpContext.Current?.Server.MapPath("~/App_Data/Logs") ?? "Logs";
                    if (!Directory.Exists(logDirectory))
                    {
                        Directory.CreateDirectory(logDirectory);
                    }

                    var logFile = Path.Combine(logDirectory, $"{category.ToLower()}.log");
                    var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    var logEntry = $"[{timestamp}] [{level}] [{category}] {message}";

                    if (exception != null)
                    {
                        logEntry += $"\nException: {exception.Message}\nStackTrace: {exception.StackTrace}";
                    }

                    logEntry += "\n" + new string('-', 50) + "\n";

                    File.AppendAllText(logFile, logEntry);
                }
            }
            catch
            {
                // 如果日志记录失败，忽略错误
            }
        }

        public static void LogApiRequest(string method, string url, string userAgent, string ipAddress, int? statusCode = null)
        {
            LogInfo($"API Request: {method} {url} | UserAgent: {userAgent} | IP: {ipAddress} | Status: {statusCode}", "Api");
        }

        public static void LogApiResponse(string method, string url, long responseTime, int statusCode, string errorMessage = null)
        {
            var message = $"API Response: {method} {url} | Time: {responseTime}ms | Status: {statusCode}";
            if (!string.IsNullOrEmpty(errorMessage))
            {
                message += $" | Error: {errorMessage}";
            }
            
            if (statusCode >= 400)
            {
                LogError(message, "Api");
            }
            else
            {
                LogInfo(message, "Api");
            }
        }

        public static void LogDatabaseQuery(string query, long executionTime, bool isSlowQuery = false)
        {
            var message = $"Database Query: {executionTime}ms | Query: {query}";
            
            if (isSlowQuery)
            {
                LogWarning(message, "Database");
            }
            else
            {
                LogDebug(message, "Database");
            }
        }

        public static void LogDeviceCollection(int deviceId, string deviceCode, bool success, string errorMessage = null)
        {
            var message = $"Device Collection: DeviceId={deviceId}, DeviceCode={deviceCode}, Success={success}";
            if (!string.IsNullOrEmpty(errorMessage))
            {
                message += $", Error: {errorMessage}";
            }

            if (success)
            {
                LogInfo(message, "Collection");
            }
            else
            {
                LogError(message, "Collection");
            }
        }

        public static void LogSecurityEvent(string eventType, string username, string ipAddress, string details)
        {
            var message = $"Security Event: Type={eventType}, User={username}, IP={ipAddress}, Details={details}";
            LogWarning(message, "Security");
        }

        public static void LogPerformanceMetric(string metricName, decimal metricValue, string unit)
        {
            var message = $"Performance Metric: {metricName}={metricValue}{unit}";
            LogDebug(message, "Performance");
        }

        public static void LogAlarmEvent(string alarmType, string alarmLevel, string message, int? deviceId = null)
        {
            var logMessage = $"Alarm: Type={alarmType}, Level={alarmLevel}, Message={message}";
            if (deviceId.HasValue)
            {
                logMessage += $", DeviceId={deviceId.Value}";
            }
            
            LogWarning(logMessage, "Alarm");
        }

        public static void LogSystemHealthCheck(DateTime checkTime, bool healthy, string issues = null)
        {
            var message = $"Health Check: Time={checkTime:yyyy-MM-dd HH:mm:ss}, Healthy={healthy}";
            if (!string.IsNullOrEmpty(issues))
            {
                message += $", Issues: {issues}";
            }

            if (healthy)
            {
                LogInfo(message, "Health");
            }
            else
            {
                LogWarning(message, "Health");
            }
        }

        public static void LogSystemStartup(DateTime startTime, string environment)
        {
            var message = $"System Startup: Time={startTime:yyyy-MM-dd HH:mm:ss}, Environment={environment}";
            LogInfo(message, "System");
        }

        public static void LogSystemShutdown(DateTime shutdownTime)
        {
            var message = $"System Shutdown: Time={shutdownTime:yyyy-MM-dd HH:mm:ss}";
            LogInfo(message, "System");
        }

        public static void LogError(Exception ex, string category = "General")
        {
            Log("ERROR", ex.Message, category, ex);
        }

        public static void LogError(string message, Exception ex, string category = "General")
        {
            Log("ERROR", message, category, ex);
        }
    }

    public class LogHelper
    {
        public static void Info(string message, string category = "General")
        {
            Logger.LogInfo(message, category);
        }

        public static void Warning(string message, string category = "General")
        {
            Logger.LogWarning(message, category);
        }

        public static void Error(string message, string category = "General")
        {
            Logger.LogError(message, category);
        }

        public static void Debug(string message, string category = "General")
        {
            Logger.LogDebug(message, category);
        }

        public static void Error(Exception ex, string category = "General")
        {
            Logger.LogError(ex, category);
        }

        public static void Error(string message, Exception ex, string category = "General")
        {
            Logger.LogError(message, ex, category);
        }
    }
}