using Hc900Crawler.Core.Application.Interfaces;

namespace Hc900Crawler.Infrastructure.Mcp;

/// <summary>
/// IMcpService 구현체 — McpClient를 통해 Python MCP 서버와 통신한다.
/// 모든 HTTP/JSON 로직은 McpClient에 위임하고,
/// 이 클래스는 McpQueryResult 래핑만 담당한다.
/// </summary>
public class McpService : IMcpService
{
    private readonly McpClient _client;

    public McpService(McpClient client)
    {
        _client = client;
    }

    public Task<bool> PingAsync() => _client.PingAsync();

    public async Task<List<McpToolDto>> ListToolsAsync()
    {
        var tools = await _client.ListToolsAsync();
        return tools.Select(t => new McpToolDto { Name = t.Name, Description = t.Description }).ToList();
    }

    public async Task<McpQueryResult> RunSqlAsync(string sql)
    {
        try
        {
            var data = await _client.RunSqlAsync(sql);
            return new McpQueryResult { Success = true, Data = data };
        }
        catch (Exception ex)
        {
            return new McpQueryResult { Success = false, Error = ex.Message };
        }
    }

    public async Task<McpQueryResult> QueryPvHistoryAsync(
        List<string> tagNames, string timeFrom, string timeTo, int limit = 100)
    {
        try
        {
            var data = await _client.QueryPvHistoryAsync(tagNames, timeFrom, timeTo, limit);
            return new McpQueryResult { Success = true, Data = data };
        }
        catch (Exception ex)
        {
            return new McpQueryResult { Success = false, Error = ex.Message };
        }
    }

    public async Task<McpQueryResult> GetTagMetadataAsync(string query, int limit = 10)
    {
        try
        {
            var data = await _client.GetTagMetadataAsync(query, limit);
            return new McpQueryResult { Success = true, Data = data };
        }
        catch (Exception ex)
        {
            return new McpQueryResult { Success = false, Error = ex.Message };
        }
    }

    public async Task<McpQueryResult> ListDrawingsAsync(string? unitNo = null)
    {
        try
        {
            var data = await _client.ListDrawingsAsync(unitNo);
            return new McpQueryResult { Success = true, Data = data };
        }
        catch (Exception ex)
        {
            return new McpQueryResult { Success = false, Error = ex.Message };
        }
    }

    public async Task<McpQueryResult> QueryWithNlAsync(string question)
    {
        try
        {
            var data = await _client.QueryWithNlAsync(question);
            return new McpQueryResult { Success = true, Data = data };
        }
        catch (Exception ex)
        {
            return new McpQueryResult { Success = false, Error = ex.Message };
        }
    }
}
