using System;
using System.Collections.Concurrent;
using System.IO;
using System.Text;

namespace StandardScene.Magnetic.Tasking
{
    /// <summary>
    /// Mag2Car 本地文件日志，按协议车号分目录：logs/car{VehicleCode}/mag2_yyyyMMdd.log
    /// </summary>
    public static class Mag2CarFileLogger
    {
        private static readonly ConcurrentDictionary<ushort, object> CarLocks = new ConcurrentDictionary<ushort, object>();
        private static string _baseDirectory = "logs";
        private static bool _enabled = true;

        public static void Configure(string baseDirectory, bool enabled)
        {
            _baseDirectory = string.IsNullOrWhiteSpace(baseDirectory) ? "logs" : baseDirectory.Trim();
            _enabled = enabled;
        }

        public static string GetCarLogDirectory(ushort vehicleCode)
        {
            return Path.Combine(ResolveBaseDirectory(), $"car{vehicleCode}");
        }

        public static string GetCurrentLogFilePath(ushort vehicleCode)
        {
            var fileName = $"mag2_{DateTime.Now:yyyyMMdd}.log";
            return Path.Combine(GetCarLogDirectory(vehicleCode), fileName);
        }

        public static void Write(ushort vehicleCode, string message)
        {
            if (!_enabled || vehicleCode == 0 || string.IsNullOrWhiteSpace(message))
            {
                return;
            }

            var carLock = CarLocks.GetOrAdd(vehicleCode, _ => new object());
            lock (carLock)
            {
                var directory = GetCarLogDirectory(vehicleCode);
                Directory.CreateDirectory(directory);
                var path = GetCurrentLogFilePath(vehicleCode);
                File.AppendAllText(
                    path,
                    $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {message}{Environment.NewLine}",
                    new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
            }
        }

        private static string ResolveBaseDirectory()
        {
            return Path.IsPathRooted(_baseDirectory)
                ? _baseDirectory
                : Path.Combine(AppContext.BaseDirectory, _baseDirectory);
        }
    }
}
