using System;
using System.Net;
using System.Text;
using System.Threading;
using Newtonsoft.Json;
using CncCollector.Core;
using log4net;

namespace CncCollector.Api
{
    /// <summary>
    /// 采集服务管理API HTTP服务。
    /// 使用 HttpListener 提供轻量管理接口，支持启停控制和状态查询。
    /// </summary>
    public class CollectorApiServer
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(CollectorApiServer));

        private readonly CollectorEngine _engine;
        private readonly string _apiKey;
        private readonly int _port;
        private HttpListener _listener;
        private Thread _listenerThread;
        private volatile bool _running;

        /// <summary>
        /// 初始化管理API服务
        /// </summary>
        /// <param name="engine">采集引擎实例</param>
        /// <param name="apiKey">API Key（用于认证）</param>
        /// <param name="port">监听端口</param>
        public CollectorApiServer(CollectorEngine engine, string apiKey, int port)
        {
            _engine = engine;
            _apiKey = apiKey;
            _port = port;
        }

        /// <summary>
        /// 启动HTTP监听
        /// </summary>
        public void Start()
        {
            if (_running) return;

            try
            {
                _listener = new HttpListener();
                _listener.Prefixes.Add($"http://+:{_port}/api/collector/");
                _listener.Start();
                _running = true;

                _listenerThread = new Thread(() =>
                {
                    while (_running)
                    {
                        try
                        {
                            var context = _listener.GetContext();
                            ThreadPool.QueueUserWorkItem(_ => ProcessRequest(context));
                        }
                        catch (HttpListenerException) { break; }
                        catch (ObjectDisposedException) { break; }
                    }
                }) { IsBackground = true };
                _listenerThread.Start();

                _log.Info($"管理API已启动: http://localhost:{_port}/api/collector/");
            }
            catch (Exception ex)
            {
                _log.Error($"管理API启动失败（端口={_port}）", ex);
            }
        }

        /// <summary>
        /// 停止HTTP监听
        /// </summary>
        public void Stop()
        {
            _running = false;
            try { _listener?.Stop(); } catch { }
            _log.Info("管理API已停止");
        }

        /// <summary>
        /// 处理单个HTTP请求
        /// </summary>
        private void ProcessRequest(HttpListenerContext ctx)
        {
            string path = ctx.Request.Url.AbsolutePath.TrimEnd('/').ToLower();
            string method = ctx.Request.HttpMethod;

            try
            {
                // API Key 认证
                string apiKeyHeader = ctx.Request.Headers["X-Api-Key"];
                if (string.IsNullOrEmpty(apiKeyHeader) || apiKeyHeader != _apiKey)
                {
                    SendJson(ctx, 401, new { code = 40101, message = "API Key无效", data = (object)null });
                    return;
                }

                // 路由
                if (path == "/api/collector/status" && method == "GET")
                {
                    var status = _engine.GetStatus();
                    SendSuccess(ctx, status);
                }
                else if (path == "/api/collector/start" && method == "POST")
                {
                    _engine.Start();
                    SendSuccess(ctx, new { message = "采集服务已启动" });
                }
                else if (path == "/api/collector/stop" && method == "POST")
                {
                    _engine.Stop();
                    SendSuccess(ctx, new { message = "采集服务已停止" });
                }
                else if (path == "/api/collector/refresh" && method == "POST")
                {
                    _engine.Refresh();
                    SendSuccess(ctx, new { message = "配置已刷新" });
                }
                else if (path == "/api/collector/daily-summary" && method == "POST")
                {
                    // 读取请求体中的日期参数，默认今天
                    string body = ReadRequestBody(ctx);
                    DateTime summaryDate = DateTime.Today;
                    if (!string.IsNullOrEmpty(body))
                    {
                        try
                        {
                            var obj = Newtonsoft.Json.Linq.JObject.Parse(body);
                            var dateStr = obj["date"]?.ToString();
                            if (!string.IsNullOrEmpty(dateStr)) summaryDate = DateTime.Parse(dateStr);
                        }
                        catch { }
                    }
                    _engine.RunDailySummary(summaryDate);
                    SendSuccess(ctx, new { message = $"日终汇总已执行（日期={summaryDate:yyyy-MM-dd}）" });
                }
                else
                {
                    SendJson(ctx, 404, new { code = 40400, message = "未知端点", data = (object)null });
                }
            }
            catch (Exception ex)
            {
                _log.Error("处理API请求异常", ex);
                SendJson(ctx, 500, new { code = 50001, message = ex.Message, data = (object)null });
            }
        }

        /// <summary>
        /// 发送成功响应
        /// </summary>
        private void SendSuccess(HttpListenerContext ctx, object data)
        {
            SendJson(ctx, 200, new { code = 0, message = "success", data });
        }

        /// <summary>
        /// 发送JSON响应
        /// </summary>
        private void SendJson(HttpListenerContext ctx, int statusCode, object obj)
        {
            try
            {
                string json = JsonConvert.SerializeObject(obj);
                byte[] bytes = Encoding.UTF8.GetBytes(json);
                ctx.Response.StatusCode = statusCode;
                ctx.Response.ContentType = "application/json; charset=utf-8";
                ctx.Response.ContentLength64 = bytes.Length;
                ctx.Response.OutputStream.Write(bytes, 0, bytes.Length);
                ctx.Response.OutputStream.Close();
            }
            catch { }
        }

        /// <summary>
        /// 读取请求体
        /// </summary>
        private string ReadRequestBody(HttpListenerContext ctx)
        {
            try
            {
                using (var reader = new System.IO.StreamReader(ctx.Request.InputStream, Encoding.UTF8))
                {
                    return reader.ReadToEnd();
                }
            }
            catch { return ""; }
        }
    }
}
