using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using CncService;
using CncService.Models;
using CncService.LogAnalyzer;

namespace CncWebApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class LogIngestionController : ControllerBase
    {
        private readonly ILogIngestionService _logIngestionService;

        public LogIngestionController(ILogIngestionService logIngestionService)
        {
            _logIngestionService = logIngestionService;
        }

        [HttpPost("ingest")]
        public async Task<IActionResult> Ingest([FromBody] LogIngestionRequest request)
        {
            if (request == null)
                return BadRequest("请求为空");

            var record = new LogRecord
            {
                LogId = request.LogId,
                MachineId = request.MachineId,
                ProgramName = request.ProgramName,
                LogTime = request.LogTime ?? DateTime.UtcNow,
                Action = request.Action,
                Result = request.Result,
                RawData = request.RawData
            };

            var analysis = new LogAnalysisResult
            {
                Summary = request.AnalysisSummary,
                DetailsJson = request.DetailsJson,
                Confidence = request.Confidence
            };

            var ok = await _logIngestionService.WriteLogAsync(record, analysis);
            if (ok)
            {
                return Ok(new { success = true, logId = record.LogId, analysisSummary = analysis.Summary });
            }
            return StatusCode(500, new { success = false, message = "写入失败" });
        }
    }

    public class LogIngestionRequest
    {
        public long LogId { get; set; }
        public string MachineId { get; set; }
        public string ProgramName { get; set; }
        public DateTime? LogTime { get; set; }
        public string Action { get; set; }
        public string Result { get; set; }
        public string RawData { get; set; }
        public string AnalysisSummary { get; set; }
        public string DetailsJson { get; set; }
        public double? Confidence { get; set; }
    }
}
