package vfs

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

var scratch = os.Getenv("VCOM_SCRATCH")

func TestArchiveSelfTruncate(t *testing.T) {
	d := filepath.Join(scratch, "arch1")
	os.RemoveAll(d)
	os.MkdirAll(d, 0o755)
	src := filepath.Join(d, "data.tar")
	os.WriteFile(src, make([]byte, 100000), 0o644)
	name := ArchiveName([]string{src}, "tar")
	target := filepath.Join(d, name)
	err := CreateArchive(context.Background(), []string{src}, target, nil)
	st, _ := os.Stat(src)
	t.Logf("archive data.tar as tar into same dir: name=%s err=%v source size now=%d (was 100000)", name, err, st.Size())
}

func TestArchiveSelfInclude(t *testing.T) {
	d := filepath.Join(scratch, "arch2")
	os.RemoveAll(d)
	os.MkdirAll(filepath.Join(d, "proj"), 0o755)
	os.WriteFile(filepath.Join(d, "proj", "a.bin"), make([]byte, 1<<20), 0o644)
	target := filepath.Join(d, "proj", "proj.zip") // passive pane inside source dir
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	err := CreateArchive(ctx, []string{filepath.Join(d, "proj")}, target, nil)
	st, _ := os.Stat(target)
	t.Logf("archive proj into proj/: err=%v archive size=%d", err, st.Size())
	os.RemoveAll(d)
}

func TestExtractOverwrite(t *testing.T) {
	d := filepath.Join(scratch, "arch3")
	os.RemoveAll(d)
	os.MkdirAll(filepath.Join(d, "src"), 0o755)
	os.WriteFile(filepath.Join(d, "src", "f.txt"), []byte("NEW"), 0o644)
	arc := filepath.Join(d, "a.zip")
	CreateArchive(context.Background(), []string{filepath.Join(d, "src", "f.txt")}, arc, nil)
	os.MkdirAll(filepath.Join(d, "dst"), 0o755)
	os.WriteFile(filepath.Join(d, "dst", "f.txt"), []byte("PRECIOUS"), 0o644)
	err := ExtractArchiveToDir(context.Background(), arc, filepath.Join(d, "dst"), nil)
	b, _ := os.ReadFile(filepath.Join(d, "dst", "f.txt"))
	t.Logf("extract over existing file: err=%v content=%q", err, b)
}

func BenchmarkListDir20k(b *testing.B) {
	for i := 0; i < b.N; i++ {
		ListDir(filepath.Join(scratch, "big"), ListOptions{ShowHidden: true, DirsFirst: true, SortBy: "name"})
	}
}

func BenchmarkReadDirOnly20k(b *testing.B) {
	for i := 0; i < b.N; i++ {
		es, _ := os.ReadDir(filepath.Join(scratch, "big"))
		for _, e := range es {
			e.Info()
		}
	}
}

func BenchmarkPreviewHighlight64k(b *testing.B) {
	p := filepath.Join(scratch, "big.go")
	for i := 0; i < b.N; i++ {
		BuildPreview(Entry{Name: "big.go", Path: p, Extension: "go"}, PreviewOptions{MaxPreviewBytes: 65536, ThemeName: "catppuccin-mocha"})
	}
}

func BenchmarkPreviewDir20k(b *testing.B) {
	p := filepath.Join(scratch, "big")
	for i := 0; i < b.N; i++ {
		BuildPreview(Entry{Name: "big", Path: p, IsDir: true}, PreviewOptions{MaxPreviewBytes: 65536, DirectoryPreviewLimit: 80})
	}
}
