package logview

import (
	"bytes"
	"os"
	"strings"
	"time"
)

// TailResult contains a bounded view of a text log file.
type TailResult struct {
	Lines     []string
	UpdatedAt time.Time
	Size      int64
}

// TailFile returns at most limit trailing lines from path. The log files AgentTeam
// writes are already rotation-bounded, so reading the active file keeps this
// helper simple and avoids platform-specific seek edge cases.
func TailFile(path string, limit int) (TailResult, error) {
	if limit < 0 {
		limit = 0
	}
	info, err := os.Stat(path)
	if err != nil {
		return TailResult{}, err
	}
	if info.Size() == 0 || limit == 0 {
		return TailResult{UpdatedAt: info.ModTime(), Size: info.Size()}, nil
	}
	data, err := os.ReadFile(path)
	if err != nil {
		return TailResult{}, err
	}
	lines := splitLogLines(data)
	if len(lines) > limit {
		lines = lines[len(lines)-limit:]
	}
	return TailResult{Lines: lines, UpdatedAt: info.ModTime(), Size: info.Size()}, nil
}

func splitLogLines(data []byte) []string {
	data = bytes.TrimSuffix(data, []byte("\n"))
	if len(data) == 0 {
		return nil
	}
	rawLines := bytes.Split(data, []byte("\n"))
	lines := make([]string, 0, len(rawLines))
	for _, raw := range rawLines {
		lines = append(lines, strings.TrimSuffix(string(raw), "\r"))
	}
	return lines
}
