using Nexus.Api.Data;
using Nexus.Api.DTOs;
using Nexus.Api.Models;

namespace Nexus.Api.Services;

/// <summary>
/// Structured backend bridge for agent/task commands.
/// Provides a clean, typed API for agents (Iris and sub-agents) to interact
/// with the task board, activity log, and delegation workflow.
///
/// This is the internal service layer — never exposed directly to the browser.
/// The GatewayBridgeController wraps this for agent-facing HTTP access.
/// </summary>
public interface ITaskBridgeService
{
    // ── Task CRUD (Agent-Commands) ──

    /// <summary>
    /// Creates a new top-level task (parent or standalone).
    /// Returns the created task DTO.
    /// </summary>
    Task<TaskBridgeResult<DashboardTaskDto>> CreateTaskAsync(
        string title,
        string? detail = null,
        string? source = "iris",
        string? priority = "Normal",
        string? assignedTo = null,
        Guid? projectId = null,
        CancellationToken ct = default);

    /// <summary>
    /// Creates a child task linked to an existing parent.
    /// This is the primary delegation command: iris creates a child task,
    /// assigns it to a sub-agent, and tracks it on the board.
    /// </summary>
    Task<TaskBridgeResult<DashboardTaskDto>> CreateChildTaskAsync(
        Guid parentTaskId,
        string title,
        string? detail = null,
        string? source = "iris",
        string? priority = "Normal",
        string? assignedTo = null,
        string? expectedFrom = null,
        bool startsInProgress = false,
        CancellationToken ct = default);

    /// <summary>
    /// Updates the status/state of a task.
    /// Enforces CanChangeState rules (only iris/bao/nexus-system may change state).
    /// </summary>
    Task<TaskBridgeResult<DashboardTaskDto>> UpdateStatusAsync(
        Guid taskId,
        string state,
        string? callerAgent = null,
        CancellationToken ct = default);

    /// <summary>
    /// Appends an activity entry to a task (comment, status note, agent note).
    /// Used by agents to annotate their progress on the board.
    /// </summary>
    Task<TaskBridgeResult<ActivityEvent>> AppendActivityAsync(
        Guid taskId,
        string message,
        string? type = "comment",
        CancellationToken ct = default);

    /// <summary>
    /// Handles a task handoff: sets ExpectedFrom to the target agent,
    /// appends a handoff activity entry, and optionally updates assigned-to.
    /// </summary>
    Task<TaskBridgeResult<DashboardTaskDto>> HandoffAsync(
        Guid taskId,
        string targetAgent,
        string? note = null,
        CancellationToken ct = default);

    // ── Query (Read) ──

    /// <summary>
    /// Returns the full task board state (grouped by status column).
    /// </summary>
    Task<BoardResponse> GetBoardAsync(CancellationToken ct = default);

    /// <summary>
    /// Returns a single task by ID.
    /// </summary>
    Task<TaskBridgeResult<DashboardTaskDto>> GetTaskAsync(
        Guid taskId,
        CancellationToken ct = default);

    /// <summary>
    /// Returns all child tasks for a given parent task.
    /// </summary>
    Task<IReadOnlyList<DashboardTaskDto>> GetChildTasksAsync(
        Guid parentTaskId,
        CancellationToken ct = default);

    /// <summary>
    /// Returns task activity history.
    /// </summary>
    Task<List<ActivityEvent>> GetTaskActivityAsync(
        Guid taskId,
        CancellationToken ct = default);

    // ── Agent Workflow ──

    /// <summary>
    /// Returns the agent-workflow overview: who is expected to respond,
    /// stale tasks, workload distribution.
    /// </summary>
    Task<AgentWorkflowOverview> GetAgentOverviewAsync(
        TimeSpan? staleThreshold = null,
        CancellationToken ct = default);
}

/// <summary>
/// Result pattern for task-bridge operations.
/// WorkTask? is null on NotFound; state is stored in the Outcome.
/// </summary>
public sealed record TaskBridgeResult<T>(
    TaskBridgeOutcome Outcome,
    T? Data = default,
    string? Error = null
);

public enum TaskBridgeOutcome
{
    Success,
    NotFound,
    InvalidState,
    Unauthorized,
    ValidationError
}
