package system

import (
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"

	"github.com/tidbcloud/AgentTeam/desktop/internal/logview"
	"github.com/tidbcloud/AgentTeam/desktop/internal/profile"
)

const (
	defaultDaemonLogTailLines = 500
	maxDaemonLogTailLines     = 1000
)

// DaemonLogHandler returns a bounded tail of the active AgentTeam daemon log file.
type DaemonLogHandler struct{}

// NewDaemonLogHandler creates a new DaemonLogHandler.
func NewDaemonLogHandler() gin.HandlerFunc {
	return (&DaemonLogHandler{}).Handle
}

// DaemonLogResponse is the JSON response for GET /logs/daemon.
type DaemonLogResponse struct {
	Path      string   `json:"path"`
	Exists    bool     `json:"exists"`
	Limit     int      `json:"limit"`
	Lines     []string `json:"lines"`
	UpdatedAt string   `json:"updatedAt,omitempty"`
	Size      int64    `json:"size"`
}

func (h *DaemonLogHandler) Handle(c *gin.Context) {
	cfg, err := profile.Load(profile.Path())
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	limit := daemonLogLimit(c.Query("tail"))
	logPath := strings.TrimSpace(cfg.LogFile())
	result, err := logview.TailFile(logPath, limit)
	if err != nil {
		if os.IsNotExist(err) {
			c.JSON(http.StatusOK, DaemonLogResponse{
				Path:   logPath,
				Exists: false,
				Limit:  limit,
				Lines:  []string{},
			})
			return
		}
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, DaemonLogResponse{
		Path:      logPath,
		Exists:    true,
		Limit:     limit,
		Lines:     result.Lines,
		UpdatedAt: result.UpdatedAt.UTC().Format(time.RFC3339),
		Size:      result.Size,
	})
}

func daemonLogLimit(raw string) int {
	trimmed := strings.TrimSpace(raw)
	if trimmed == "" {
		return defaultDaemonLogTailLines
	}
	limit, err := strconv.Atoi(trimmed)
	if err != nil || limit <= 0 {
		return defaultDaemonLogTailLines
	}
	if limit > maxDaemonLogTailLines {
		return maxDaemonLogTailLines
	}
	return limit
}
