using System;
using System.Configuration;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using CncModels.Dto;
using CncWebApi.Infrastructure;
using Newtonsoft.Json;

namespace CncWebApi.Controllers
{
    /// <summary>
    /// 模拟采集服务控制器。
    /// 将所有请求转发到 CncSimulator（localhost:9000网关 + 动态端口单地址）。
    /// </summary>
    [RoutePrefix("api/admin/simulator")]
    [JwtAuthFilter]
    public class SimulatorController : ApiController
    {
        private static readonly HttpClient _httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
        private static readonly string _gatewayUrl = ConfigurationManager.AppSettings["SimulatorGatewayUrl"] ?? "http://localhost:9000";

        #region 网关API（→ localhost:9000）

        /// <summary>
        /// 探测模拟器是否运行
        /// GET /api/admin/simulator/ping
        /// </summary>
        [HttpGet]
        [Route("ping")]
        public IHttpActionResult Ping()
        {
            try
            {
                var response = _httpClient.GetAsync($"{_gatewayUrl}/admin/api/status").Result;
                return Ok(ApiResponse<object>.Success(new { running = response.IsSuccessStatusCode }));
            }
            catch
            {
                return Ok(ApiResponse<object>.Success(new { running = false }));
            }
        }

        /// <summary>
        /// 获取数据库采集地址列表
        /// GET /api/admin/simulator/addresses
        /// </summary>
        [HttpGet]
        [Route("addresses")]
        public IHttpActionResult GetAddresses()
        {
            return ForwardToGateway("/admin/api/db-addresses");
        }

        /// <summary>
        /// 获取所有模拟状态汇总
        /// GET /api/admin/simulator/status
        /// </summary>
        [HttpGet]
        [Route("status")]
        public IHttpActionResult GetStatus()
        {
            return ForwardToGateway("/admin/api/status");
        }

        /// <summary>
        /// 启动指定地址的模拟
        /// POST /api/admin/simulator/start
        /// </summary>
        [HttpPost]
        [Route("start")]
        public IHttpActionResult Start()
        {
            return ForwardToGatewayPost("/admin/api/start-address");
        }

        /// <summary>
        /// 停止指定地址的模拟
        /// POST /api/admin/simulator/stop
        /// </summary>
        [HttpPost]
        [Route("stop")]
        public IHttpActionResult Stop()
        {
            return ForwardToGatewayPost("/admin/api/stop-address");
        }

        /// <summary>
        /// 启动所有地址的模拟
        /// POST /api/admin/simulator/start-all
        /// </summary>
        [HttpPost]
        [Route("start-all")]
        public IHttpActionResult StartAll()
        {
            return ForwardToGatewayPost("/admin/api/start-all");
        }

        /// <summary>
        /// 停止所有地址的模拟
        /// POST /api/admin/simulator/stop-all
        /// </summary>
        [HttpPost]
        [Route("stop-all")]
        public IHttpActionResult StopAll()
        {
            return ForwardToGatewayPost("/admin/api/stop-all");
        }

        /// <summary>
        /// 重新加载数据库配置
        /// POST /api/admin/simulator/reload
        /// </summary>
        [HttpPost]
        [Route("reload")]
        public IHttpActionResult Reload()
        {
            return ForwardToGatewayPost("/admin/api/reload-db");
        }

        #endregion

        #region 单地址API（→ localhost:{port}）

        /// <summary>
        /// 获取单地址状态
        /// GET /api/admin/simulator/address/{port}/status
        /// </summary>
        [HttpGet]
        [Route("address/{port}/status")]
        public IHttpActionResult GetAddressStatus(int port)
        {
            return ForwardToAddress(port, "/admin/api/status");
        }

        /// <summary>
        /// 启动单地址数据模拟
        /// POST /api/admin/simulator/address/{port}/start
        /// </summary>
        [HttpPost]
        [Route("address/{port}/start")]
        public IHttpActionResult StartAddress(int port)
        {
            return ForwardToAddressPost(port, "/admin/api/start");
        }

        /// <summary>
        /// 停止单地址数据模拟
        /// POST /api/admin/simulator/address/{port}/stop
        /// </summary>
        [HttpPost]
        [Route("address/{port}/stop")]
        public IHttpActionResult StopAddress(int port)
        {
            return ForwardToAddressPost(port, "/admin/api/stop");
        }

        /// <summary>
        /// 触发设备事件
        /// POST /api/admin/simulator/address/{port}/event
        /// </summary>
        [HttpPost]
        [Route("address/{port}/event")]
        public IHttpActionResult TriggerEvent(int port)
        {
            return ForwardToAddressPost(port, "/admin/api/event");
        }

        /// <summary>
        /// 修改数据变化频率
        /// POST /api/admin/simulator/address/{port}/interval
        /// </summary>
        [HttpPost]
        [Route("address/{port}/interval")]
        public IHttpActionResult SetInterval(int port)
        {
            return ForwardToAddressPost(port, "/admin/api/interval");
        }

        /// <summary>
        /// 设置网络异常类型
        /// POST /api/admin/simulator/address/{port}/network
        /// </summary>
        [HttpPost]
        [Route("address/{port}/network")]
        public IHttpActionResult SetNetwork(int port)
        {
            return ForwardToAddressPost(port, "/admin/api/network");
        }

        /// <summary>
        /// 切换剧本模式
        /// POST /api/admin/simulator/address/{port}/mode
        /// </summary>
        [HttpPost]
        [Route("address/{port}/mode")]
        public IHttpActionResult SetMode(int port)
        {
            return ForwardToAddressPost(port, "/admin/api/mode");
        }

        /// <summary>
        /// 获取请求日志
        /// GET /api/admin/simulator/address/{port}/logs
        /// </summary>
        [HttpGet]
        [Route("address/{port}/logs")]
        public IHttpActionResult GetLogs(int port)
        {
            return ForwardToAddress(port, "/admin/api/logs");
        }

        /// <summary>
        /// 获取零件统计
        /// GET /api/admin/simulator/address/{port}/stats
        /// </summary>
        [HttpGet]
        [Route("address/{port}/stats")]
        public IHttpActionResult GetStats(int port)
        {
            return ForwardToAddress(port, "/admin/api/stats");
        }

        /// <summary>
        /// 添加设备
        /// POST /api/admin/simulator/address/{port}/add-device
        /// </summary>
        [HttpPost]
        [Route("address/{port}/add-device")]
        public IHttpActionResult AddDevice(int port)
        {
            return ForwardToAddressPost(port, "/admin/api/add-device");
        }

        /// <summary>
        /// 移除设备
        /// POST /api/admin/simulator/address/{port}/remove-device
        /// </summary>
        [HttpPost]
        [Route("address/{port}/remove-device")]
        public IHttpActionResult RemoveDevice(int port)
        {
            return ForwardToAddressPost(port, "/admin/api/remove-device");
        }

        /// <summary>
        /// 获取事件历史
        /// GET /api/admin/simulator/address/{port}/event-history
        /// </summary>
        [HttpGet]
        [Route("address/{port}/event-history")]
        public IHttpActionResult GetEventHistory(int port)
        {
            return ForwardToAddress(port, "/admin/api/event-history");
        }

        /// <summary>
        /// 获取完整汇总
        /// GET /api/admin/simulator/address/{port}/full-summary
        /// </summary>
        [HttpGet]
        [Route("address/{port}/full-summary")]
        public IHttpActionResult GetFullSummary(int port)
        {
            return ForwardToAddress(port, "/admin/api/full-summary");
        }

        /// <summary>
        /// 获取异常日志
        /// GET /api/admin/simulator/address/{port}/error-log
        /// </summary>
        [HttpGet]
        [Route("address/{port}/error-log")]
        public IHttpActionResult GetErrorLog(int port)
        {
            return ForwardToAddress(port, "/admin/api/error-log");
        }

        #endregion

        #region 转发辅助方法

        /// <summary>
        /// GET转发到网关（9000端口）
        /// </summary>
        private IHttpActionResult ForwardToGateway(string path)
        {
            try
            {
                var response = _httpClient.GetAsync($"{_gatewayUrl}{path}").Result;
                var body = response.Content.ReadAsStringAsync().Result;
                var data = JsonConvert.DeserializeObject(body);
                return Ok(ApiResponse<object>.Success(data));
            }
            catch (Exception ex)
            {
                return Ok(ApiResponse<object>.Fail(50001, $"模拟器连接失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// POST转发到网关（9000端口），透传请求体
        /// </summary>
        private IHttpActionResult ForwardToGatewayPost(string path)
        {
            try
            {
                var body = Request.Content.ReadAsStringAsync().Result;
                var request = new HttpRequestMessage(HttpMethod.Post, $"{_gatewayUrl}{path}")
                {
                    Content = new StringContent(body, Encoding.UTF8, "application/json")
                };
                var response = _httpClient.SendAsync(request).Result;
                var responseBody = response.Content.ReadAsStringAsync().Result;
                var data = JsonConvert.DeserializeObject(responseBody);
                return Ok(ApiResponse<object>.Success(data));
            }
            catch (Exception ex)
            {
                return Ok(ApiResponse<object>.Fail(50001, $"模拟器连接失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// GET转发到单地址（动态端口）
        /// </summary>
        private IHttpActionResult ForwardToAddress(int port, string path)
        {
            try
            {
                var response = _httpClient.GetAsync($"http://localhost:{port}{path}").Result;
                var body = response.Content.ReadAsStringAsync().Result;
                var data = JsonConvert.DeserializeObject(body);
                return Ok(ApiResponse<object>.Success(data));
            }
            catch (Exception ex)
            {
                return Ok(ApiResponse<object>.Fail(50001, $"模拟地址(端口{port})连接失败: {ex.Message}"));
            }
        }

        /// <summary>
        /// POST转发到单地址（动态端口），透传请求体
        /// </summary>
        private IHttpActionResult ForwardToAddressPost(int port, string path)
        {
            try
            {
                var body = Request.Content.ReadAsStringAsync().Result;
                var request = new HttpRequestMessage(HttpMethod.Post, $"http://localhost:{port}{path}")
                {
                    Content = new StringContent(body, Encoding.UTF8, "application/json")
                };
                var response = _httpClient.SendAsync(request).Result;
                var responseBody = response.Content.ReadAsStringAsync().Result;
                var data = JsonConvert.DeserializeObject(responseBody);
                return Ok(ApiResponse<object>.Success(data));
            }
            catch (Exception ex)
            {
                return Ok(ApiResponse<object>.Fail(50001, $"模拟地址(端口{port})连接失败: {ex.Message}"));
            }
        }

        #endregion
    }
}
