using System;
using System.Net.Http;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace MultiWheelC;

/// <summary>
/// Playground 仿真器 HTTP Web API 轻量客户端：查询小车位姿、瞬移小车。
/// 服务端实现见 Playground/Web/PlaygroundWebApi.cs，默认监听 http://localhost:18090。
/// 坐标单位 mm，朝向 yawDeg 单位为度，世界坐标系与场景 JSON 一致。
/// </summary>
public static class PlaygroundWebApi
{
    // 禁用系统代理：本机 Playground 走 localhost，若经系统代理(如 127.0.0.1:7890)会连接失败。
    private static readonly HttpClient Http = new HttpClient(new HttpClientHandler { UseProxy = false })
    {
        Timeout = TimeSpan.FromSeconds(3)
    };

    public struct Pose
    {
        public float X;
        public float Y;
        public float YawDeg;
    }

    /// <summary>查询单台小车的世界位姿。GET /api/robots/{name}。</summary>
    public static Pose GetPose(string baseUrl, string robotName)
    {
        var url = $"{baseUrl.TrimEnd('/')}/api/robots/{Uri.EscapeDataString(robotName)}";
        var json = Http.GetStringAsync(url).GetAwaiter().GetResult();
        var o = JObject.Parse(json);
        return new Pose
        {
            X = o.Value<float>("x"),
            Y = o.Value<float>("y"),
            YawDeg = o.Value<float>("yawDeg")
        };
    }

    /// <summary>将小车瞬移到目标世界位姿。POST /api/robots/{name}/move。</summary>
    public static void Move(string baseUrl, string robotName, float x, float y, float yawDeg)
    {
        var url = $"{baseUrl.TrimEnd('/')}/api/robots/{Uri.EscapeDataString(robotName)}/move";
        var body = JsonConvert.SerializeObject(new { x, y, yaw = yawDeg, stop = true });
        using var content = new StringContent(body, Encoding.UTF8, "application/json");
        var resp = Http.PostAsync(url, content).GetAwaiter().GetResult();
        resp.EnsureSuccessStatusCode();
    }

    /// <summary>查询车辆运动是否启用（暂停时为 false）。GET /api/motion。</summary>
    public static bool MotionEnabled(string baseUrl)
    {
        var url = $"{baseUrl.TrimEnd('/')}/api/motion";
        var json = Http.GetStringAsync(url).GetAwaiter().GetResult();
        return JObject.Parse(json).Value<bool>("motionEnabled");
    }

    /// <summary>恢复车辆运动。POST /api/motion/resume。</summary>
    public static void ResumeMotion(string baseUrl)
    {
        var url = $"{baseUrl.TrimEnd('/')}/api/motion/resume";
        var resp = Http.PostAsync(url, null).GetAwaiter().GetResult();
        resp.EnsureSuccessStatusCode();
    }

    /// <summary>
    /// 暂停车辆运动（仅冻结运动，不停止仿真；传感器继续扫描）。POST /api/motion/pause。
    /// feedback: "zero"(默认,反馈归零) / "none"(不上报) / "hold"(保留暂停瞬间值)。
    /// </summary>
    public static void PauseMotion(string baseUrl, string feedback = "zero")
    {
        var url = $"{baseUrl.TrimEnd('/')}/api/motion/pause";
        var body = JsonConvert.SerializeObject(new { feedback });
        using var content = new StringContent(body, Encoding.UTF8, "application/json");
        var resp = Http.PostAsync(url, content).GetAwaiter().GetResult();
        resp.EnsureSuccessStatusCode();
    }
}
