using molilian.core;
using dodohold.core;
using Microsoft.AspNetCore.Mvc;
using Org.BouncyCastle.Ocsp;
using System.Text.Json;
using System.Runtime.InteropServices;
using System.Net;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Authentication;
using TencentCloud.Ecm.V20190719.Models;
using COSXML.Network;
using System.Linq;
using static dodohold.core.ZTOExpress.CreateOrderArgs;
using TencentCloud.Lighthouse.V20200324.Models;
using TencentCloud.Ame.V20190916.Models;
using TencentCloud.Omics.V20221128.Models;
using System.Threading.Channels;

namespace molilian.api.Controllers
{
    [ApiController]
    [Route("api/[action]")]
    public class ApiController : ControllerBase
    {
        protected IHttpContextAccessor _accessor;
        TaokeOpenCore core;
        public ApiController(IHttpContextAccessor accessor)
        {
            _accessor = accessor;
            core = new TaokeOpenCore();
        }

        //[HttpGet]
        //public async Task<ActionResult> RequestAsync([FromQuery] string url, [FromQuery] int proxyId)
        //{
        //    if (string.IsNullOrEmpty(url))
        //    {
        //        return BadRequest("URL cannot be empty");
        //    }

        //    var proxy = ProxyNodesCore.GetOne(proxyId);
        //    if (proxy == null)
        //    {
        //        return Unauthorized("Invalid proxy configuration");
        //    }
        //    WebClientUtility cli = new()
        //    {
        //        Proxy = proxy
        //    };
        //    await cli.RequestAsync(url);
        //    var content = cli.Body();
        //    var contentType = cli.ResponseMessage.Content.Headers.ContentType?.MediaType ?? "text/plain";
        //    return Content(content, contentType);
        //}

        [HttpGet]
        public async Task<ActionResult> RequestAsync([FromQuery] string url, [FromQuery] string proxy)
        {
            if (string.IsNullOrEmpty(url))
            {
                return BadRequest("URL cannot be empty");
            }

            WebProxy _proxy = ProxyManager.Parse(proxy);
            WebClientUtility cli = new();
            cli.Proxy = _proxy;
            cli.Timeout = TimeSpan.FromSeconds(10);
            await cli.RequestAsync(url);
            if (cli.Successed)
            {
                var content = cli.Body();

                var contentType = cli.ResponseMessage.Content.Headers.ContentType?.MediaType ?? "text/plain";
                return Content(content, contentType);
            }
            throw cli.ResponseException;
        }


        [HttpGet]
        public ActionResult enable_sampling([FromQuery] int count = 1000)
        {
            int requestedCount = count;
            int remainingCount = PromotionQuerySamplingCore.EnableSampling(count);
            return new APIResult(new
            {
                success = true,
                message = remainingCount > 0 ? "ok" : "stopped",
                requestedCount,
                count = remainingCount,
                remainingCount
            });
        }

        [HttpPost]
        public async Task<ActionResult> PromotionQuery([FromBody] JsonElement form, [FromQuery] string a = "", [FromQuery] int t = 0, [FromQuery] string sign = "")
        {
            var img = form.Read("img", string.Empty);
            var url = form.Read("url", string.Empty);
            var ip = form.Read("ip", string.Empty);
            var oaid = form.Read("oaid", string.Empty);
            var scene = form.Read("scene", string.Empty);
            var recommand = form.Read("recommand", true);
            var useCouponLinkFirst = form.Read("useCouponLinkFirst", true);
            var aid = form.Read("aid", 0);

            //验证签名
            if (string.IsNullOrEmpty(a) || string.IsNullOrEmpty(sign))
            {
                return new APIResult(new { success = false, message = "验证错误" }, APIResultCodeEnum.Unauthorized);
            }

            DateTime time1 = t.Convert2Datetime();
            if (time1 < DateTime.Now.AddMinutes(-10))
            {
                return new APIResult(new { success = false, message = "验证错误2" }, APIResultCodeEnum.Unauthorized);
            }

            var account = await ApiAccountCore.GetOneAsync(a);
            if (account == null)
            {
                return new APIResult(new { success = false, message = "验证错误3" }, APIResultCodeEnum.Unauthorized);
            }
            string app_sign = $"{account.api_secret}@{t}".MD5();
            if (sign != app_sign)
            {
                return new APIResult(new { success = false, message = "验证错误4" }, APIResultCodeEnum.Unauthorized);
            }

            if (!string.IsNullOrEmpty(url))
            {
                var bytes = new WebClientUtility().Request(url).ResponseBody;
                img = Convert.ToBase64String(bytes);
            }
            var response = await core.PromotionQueryAsync(img, oaid, ip, scene, recommand, false, aid, useCouponLinkFirst);
            _ = PromotionQuerySamplingCore.TrySampleAsync(img, ip, oaid, ExtractActionResultPayload(response));
            return response;
        }


        [HttpPost]
        public async Task<ActionResult> unsafePromotionQuery([FromBody] JsonElement form)
        {
            var img = form.Read("img", string.Empty);
            var url = form.Read("url", string.Empty);
            var tkl = form.Read("tkl", string.Empty);
            var itemid = form.Read("itemid", string.Empty);
            var ip = form.Read("ip", string.Empty);
            var oaid = form.Read("oaid", string.Empty);
            var scene = form.Read("scene", string.Empty);
            var recommand = form.Read("recommand", true);
            var debug = form.Read("debug", false);
            var useCouponLinkFirst = form.Read("useCouponLinkFirst", true);
            var aid = form.Read("aid", 0);

            int count = form.Read("count", 0);

            if (!string.IsNullOrEmpty(url))
            {
                var bytes = new WebClientUtility().Request(url).ResponseBody;
                img = Convert.ToBase64String(bytes);
            }

            if (string.IsNullOrEmpty(oaid))
            {
                Random rand = new Random();
                oaid = $"{rand.Next(100000, 999999)}-{rand.Next(100000, 999999)}-{rand.Next(100000, 999999)}";
            }

            if (count > 1)
            {
                for (int i = 0; i < count; i++)
                {
                    _ = core.PromotionQueryAsync(img, oaid, ip, scene, recommand, debug, aid, useCouponLinkFirst);
                }
                return new APIResult(new { msg = "ok" });
            }

            // 从口令解析商品图 临时需求
            if (!string.IsNullOrEmpty(tkl))
            {
                string goods_url = AlimamaPlus.GetLink(tkl);
                (bool successed, string itemUrl) = AlimamaPlus.GetItemUrl(goods_url);
                if (successed && !string.IsNullOrEmpty(itemUrl))
                {
                    itemid = AlimamaPlus.ExtractItemId(itemUrl);
                    (APIResult target, PromotionQueryDTO data) = await core.PromotionQueryByItemIdAsync(itemid, oaid, ip, scene, recommand, debug, aid);


                    if (data != null)
                    {
                        url = data.PromotionImg[0].pic;
                        if (!string.IsNullOrEmpty(url))
                        {
                            var bytes = new WebClientUtility().Request(url).ResponseBody;
                            img = Convert.ToBase64String(bytes);
                        }
                    }
                    return await core.PromotionQueryAsync(img, oaid, ip, scene, recommand, debug, aid, useCouponLinkFirst);
                }

                if (!string.IsNullOrEmpty(itemid))
                {
                    (APIResult result, PromotionQueryDTO data) = await core.PromotionQueryByItemIdAsync(itemid, oaid, ip, scene, recommand, debug, aid, useCouponLinkFirst);
                    return result;
                }
            }

            return await core.PromotionQueryAsync(img, oaid, ip, scene, recommand, debug, aid, useCouponLinkFirst);

        }

        [HttpGet]
        public async Task<ActionResult> PromotionQuerySampleLogs([FromQuery] int page = 1, [FromQuery] int pageSize = 20, [FromQuery] int n = 0, [FromQuery] string keyword = "")
        {
            int resolvedPageSize = n > 0 ? n : pageSize;
            try
            {
                var result = await PromotionQuerySamplingCore.QueryLogsAsync(page, resolvedPageSize, keyword);
                return new APIResult(new
                {
                    success = true,
                    count = result.logs.Count,
                    page = result.page,
                    pageSize = result.pageSize,
                    totalCount = result.totalCount,
                    totalPages = result.totalPages,
                    remainingCount = PromotionQuerySamplingCore.GetRemainingCount(),
                    logs = result.logs
                });
            }
            catch (Exception ex)
            {
                _ = new LoggerLibrary("promotion_query_samples", "query_error")
                    .Info(ex.Message, ex.StackTrace)
                    .SaveAsync();
                return new APIResult(new
                {
                    success = false,
                    message = ex.Message,
                    count = 0,
                    page = Math.Max(page, 1),
                    pageSize = Math.Clamp(resolvedPageSize, 1, PromotionQuerySamplingCore.MaxQueryCount),
                    totalCount = 0,
                    totalPages = 0,
                    remainingCount = PromotionQuerySamplingCore.GetRemainingCount(),
                    logs = Array.Empty<object>()
                });
            }
        }

        private static string ExtractActionResultPayload(ActionResult response)
        {
            var jsonOptions = new JsonSerializerOptions
            {
                Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };

            if (response is ContentResult contentResult && !string.IsNullOrWhiteSpace(contentResult.Content))
            {
                return contentResult.Content;
            }

            if (response is JsonResult jsonResult && jsonResult.Value != null)
            {
                return JsonSerializer.Serialize(jsonResult.Value, jsonOptions);
            }

            if (response is ObjectResult objectResult && objectResult.Value != null)
            {
                return JsonSerializer.Serialize(objectResult.Value, jsonOptions);
            }

            var responseType = response.GetType();
            var contentProperty = responseType.GetProperty("Content");
            if (contentProperty?.GetValue(response) is string rawContent && !string.IsNullOrWhiteSpace(rawContent))
            {
                return rawContent;
            }

            var valueProperty = responseType.GetProperty("Value");
            var value = valueProperty?.GetValue(response);
            if (value != null)
            {
                return JsonSerializer.Serialize(value, jsonOptions);
            }

            return string.Empty;
        }

    }
}
