package server

import (
	"strings"
	"time"

	"agent/internal/agent"

	"github.com/gin-gonic/gin"
)

// coopTaskView 是返回给前端的协作任务视图，附带容器的实时状态与协作轮次进度。
type coopTaskView struct {
	ID              string    `json:"id"`
	SessionID       string    `json:"session_id"`
	Status          string    `json:"status"` // running | done
	Error           string    `json:"error,omitempty"`
	ExitCode        int       `json:"exit_code,omitempty"`
	Blackboard      string    `json:"blackboard,omitempty"`
	RoundMax        int       `json:"round_max"`
	CurrentRound    int       `json:"current_round"`
	ContainerState  string    `json:"container_state,omitempty"`
	ContainerStatus string    `json:"container_status,omitempty"`
	CreatedAt       time.Time `json:"created_at"`
	FinishedAt      time.Time `json:"finished_at,omitempty"`
}

// coopTasks 返回协作任务列表，支持 ?session=<id> 过滤到某个会话。
func (s *Server) coopTasks(c *gin.Context) {
	tasks := s.agent.CoopTasks(strings.TrimSpace(c.Query("session")))
	views := make([]coopTaskView, 0, len(tasks))
	for _, task := range tasks {
		views = append(views, s.coopTaskView(task))
	}
	ok(c, gin.H{"tasks": views})
}

func (s *Server) coopTaskView(task *agent.CoopTask) coopTaskView {
	view := coopTaskView{
		ID:         task.ID,
		SessionID:  task.SessionID,
		Status:     task.Status,
		Error:      task.Error,
		ExitCode:   task.ExitCode,
		Blackboard: task.Blackboard,
		RoundMax:   task.RoundMax,
		CreatedAt:  task.CreatedAt,
		FinishedAt: task.FinishedAt,
	}
	// 轮次进度以黑板 logs 目录实际出现的轮次为准（容器清理后日志仍在）
	view.CurrentRound = agent.CurrentCoopRound(task.Blackboard)
	if view.CurrentRound == 0 {
		view.CurrentRound = view.RoundMax
	}
	// 运行中的任务实时查询容器状态；已完成任务容器已被清理，直接读记录即可
	if task.Status == "running" && task.ContainerID != "" {
		if state, status, err := agent.ContainerInspectStatus(s.dockerCfg.Socket(), task.ContainerID); err == nil {
			view.ContainerState = state
			view.ContainerStatus = status
		}
	}
	return view
}
