using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MiGu.Server.Launcher;

namespace MiGu.Server.Controllers;

[ApiController]
[Route("api/health")]
public class HealthController : ControllerBase
{
    private static readonly DateTimeOffset StartTime = DateTimeOffset.UtcNow;
    private readonly SimpleLiteLauncher _launcher;

    public HealthController(SimpleLiteLauncher launcher) => _launcher = launcher;

    [HttpGet]
    public IActionResult Get()
    {
        return Ok(new
        {
            status = "ok",
            mode = "WebEnabled",
            startTime = StartTime,
            uptimeSec = (long)(DateTimeOffset.UtcNow - StartTime).TotalSeconds,
            ports = new
            {
                webApi = 7001,
                webSocket = 7002,
                platform = 8080,
                vrender = 8223,
                vehicle = 8222
            },
            architecture = "v1.5"
        });
    }

    /// <summary>
    /// SimpleLite 拉起配置诊断：查看当前 ExecutablePath、解析结果、端口是否已有服务。
    /// 配置位置：<c>MiGu.Server/appsettings.json</c> → <c>SimpleLite</c> 节点。
    /// </summary>
    [HttpGet("simplelite")]
    public IActionResult GetSimpleLiteDiagnostics() => Ok(_launcher.GetDiagnostics());

    /// <summary>
    /// 关闭 SimpleLite、同步最新 DLL、重新拉起。用于「前往站点」API 缺失时一键更新。
    /// </summary>
    [HttpPost("simplelite/restart-for-update")]
    [Authorize]
    public IActionResult RestartSimpleLiteForUpdate([FromQuery] string launchMode = "webonly")
    {
        var result = _launcher.RestartForUpdate(launchMode);
        var diag = _launcher.GetDiagnostics();
        return Ok(new { restart = result, diagnostics = diag });
    }
}
