using Microsoft.AspNetCore.Mvc;
using FortranWebApi.Models;
using FortranWebApi.Services;
using System.Text.Json;

namespace FortranWebApi.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class FortranCalculateController : ControllerBase
    {
        private readonly FortranInteropService _fortranService;
        private readonly ILogger<FortranCalculateController> _logger;

        public FortranCalculateController(FortranInteropService fortranService, ILogger<FortranCalculateController> logger)
        {
            _fortranService = fortranService;
            _logger = logger;
        }

        [HttpPost]
        public IActionResult Post([FromBody] FortranRequestWrapper wrapper)
        {
            try
            {
                if (string.IsNullOrEmpty(wrapper.Text))
                {
                    return BadRequest(new
                    {
                        message = "请求文本不能为空",
                        success = false,
                        data = (object)null
                    });
                }

                string result = _fortranService.ProcessFortranRequest(wrapper.Text);
                
                // 使用驼峰命名法解析结果
                var options = new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
                    PropertyNameCaseInsensitive = true,
                    WriteIndented = true
                };
                
                var resultObj = JsonSerializer.Deserialize<FortranRequest>(result, options);
                
                // 返回新的格式
                var response = new ApiResponse<FortranRequest>
                {
                    Message = "Success",
                    Success = true,
                    Data = new ApiResponseData<FortranRequest>
                    {
                        Value = resultObj
                    }
                };

                return Ok(response);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理Fortran请求时发生错误");
                return StatusCode(500, new
                {
                    message = ex.Message,
                    success = false,
                    data = (object)null
                });
            }
        }
    }
}