using Health.Domain.Entities;
using Health.Domain.Enums;

namespace Health.Application.AI;

public sealed record AiConversationDto(
    Guid Id,
    string AgentType,
    string? Title,
    string? Summary,
    int MessageCount,
    DateTime CreatedAt,
    DateTime UpdatedAt);

public sealed record AiConversationMessageDto(
    Guid Id,
    string Role,
    string Content,
    string? Intent,
    string? MetadataJson,
    DateTime CreatedAt);

public sealed record OpenConversationResult(
    bool Found,
    bool Created,
    Guid ConversationId);

public interface IAiConversationService
{
    Task<OpenConversationResult> OpenAsync(Guid userId, Guid? conversationId, AgentType agentType, string firstMessage, CancellationToken ct);
    Task AddUserMessageAsync(Guid conversationId, string content, CancellationToken ct);
    Task AddAssistantMessageAsync(Guid conversationId, string content, CancellationToken ct);
    Task<IReadOnlyList<AiConversationMessageDto>> GetRecentMessagesAsync(Guid conversationId, int limit, CancellationToken ct);
    Task<IReadOnlyList<AiConversationDto>> ListAsync(Guid userId, CancellationToken ct);
    Task<IReadOnlyList<AiConversationMessageDto>> GetMessagesAsync(Guid userId, Guid conversationId, CancellationToken ct);
    Task DeleteAsync(Guid userId, Guid conversationId, CancellationToken ct);
}

public interface IAiConversationRepository
{
    Task<Conversation?> GetOwnedAsync(Guid userId, Guid conversationId, CancellationToken ct);
    Task<Conversation?> GetAsync(Guid conversationId, CancellationToken ct);
    Task<IReadOnlyList<Conversation>> ListAsync(Guid userId, CancellationToken ct);
    Task<IReadOnlyList<ConversationMessage>> GetMessagesAsync(Guid conversationId, CancellationToken ct);
    Task<IReadOnlyList<ConversationMessage>> GetRecentMessagesAsync(Guid conversationId, int limit, CancellationToken ct);
    Task AddConversationAsync(Conversation conversation, CancellationToken ct);
    Task AddMessageAsync(ConversationMessage message, CancellationToken ct);
    void Delete(Conversation conversation);
    Task SaveChangesAsync(CancellationToken ct);
}

public interface IPatientContextService
{
    Task<string> BuildAsync(Guid userId, CancellationToken ct);
}

public sealed record AiConfirmedWriteResult(int Code, object? Data, string? Message);

public interface IAiToolExecutionService
{
    Task<object> ExecuteAsync(string toolName, string arguments, Guid userId, CancellationToken ct);
    Task<AiConfirmedWriteResult> ConfirmAsync(Guid commandId, Guid userId, CancellationToken ct);
}
