package logger

import (
	"context"
	"os"
	"path/filepath"
	"testing"
	"time"
)

func TestCleanOldLogs(t *testing.T) {
	dir := t.TempDir()
	agentDir := filepath.Join(dir, "bot1")
	os.MkdirAll(agentDir, 0o755)

	now := time.Now().UTC()
	oldDate := now.AddDate(0, 0, -10).Format("2006-01-02")   // 10 days ago → should be removed
	recentDate := now.AddDate(0, 0, -5).Format("2006-01-02") // 5 days ago → should remain
	todayDate := now.Format("2006-01-02")                     // today → should remain

	files := []string{
		oldDate + ".jsonl",
		oldDate + ".jsonl.gz",
		recentDate + ".jsonl",
		todayDate + ".jsonl",
	}
	for _, f := range files {
		os.WriteFile(filepath.Join(agentDir, f), []byte("{}"), 0o644)
	}

	// Retain 7 days → should remove files older than 7 days.
	cleanOldLogs(dir, "bot1", 7)

	remaining, _ := os.ReadDir(agentDir)
	names := make(map[string]bool)
	for _, e := range remaining {
		names[e.Name()] = true
	}

	if names[oldDate+".jsonl"] {
		t.Errorf("%s.jsonl should have been removed", oldDate)
	}
	if names[oldDate+".jsonl.gz"] {
		t.Errorf("%s.jsonl.gz should have been removed", oldDate)
	}
	if !names[recentDate+".jsonl"] {
		t.Errorf("%s.jsonl should still exist", recentDate)
	}
	if !names[todayDate+".jsonl"] {
		t.Errorf("%s.jsonl should still exist", todayDate)
	}
}

func TestParseDateFromFilename(t *testing.T) {
	tests := []struct {
		name string
		want string
	}{
		{"2026-03-06.jsonl", "2026-03-06"},
		{"2026-03-06.1.jsonl", "2026-03-06"},
		{"2026-03-06.jsonl.gz", "2026-03-06"},
		{"2026-03-06.2.jsonl.gz", "2026-03-06"},
		{"invalid.jsonl", ""},
	}
	for _, tt := range tests {
		d := parseDateFromFilename(tt.name)
		got := ""
		if !d.IsZero() {
			got = d.Format("2006-01-02")
		}
		if got != tt.want {
			t.Errorf("parseDateFromFilename(%q) = %q, want %q", tt.name, got, tt.want)
		}
	}
}

func TestCleanOldLogs_EmptyDir(t *testing.T) {
	dir := t.TempDir()
	// Should not panic on non-existent agent dir.
	cleanOldLogs(dir, "nonexistent", 7)
}

func TestIsLogFile(t *testing.T) {
	if !isLogFile("2026-03-06.jsonl") {
		t.Error("should match .jsonl")
	}
	if !isLogFile("2026-03-06.jsonl.gz") {
		t.Error("should match .jsonl.gz")
	}
	if isLogFile("readme.txt") {
		t.Error("should not match .txt")
	}
}

func TestRunCleanup_Cancellation(t *testing.T) {
	dir := t.TempDir()
	os.MkdirAll(filepath.Join(dir, "bot1"), 0o755)

	ctx, cancel := context.WithCancel(context.Background())
	done := make(chan struct{})
	go func() {
		runCleanup(ctx, dir, "bot1", 7, 50*time.Millisecond)
		close(done)
	}()

	time.Sleep(150 * time.Millisecond)
	cancel()

	select {
	case <-done:
	case <-time.After(2 * time.Second):
		t.Error("cleanup goroutine did not exit after cancel")
	}
}
