package fetch

import (
	"context"
	"crypto/sha256"
	"encoding/hex"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"testing"
)

func TestVerifyFile(t *testing.T) {
	tmpDir := t.TempDir()
	testPath := filepath.Join(tmpDir, "test.bin")
	content := []byte("hello ocr world")
	if err := os.WriteFile(testPath, content, 0644); err != nil {
		t.Fatal(err)
	}

	h := sha256.Sum256(content)
	shaStr := hex.EncodeToString(h[:])

	if !VerifyFile(testPath, shaStr, int64(len(content))) {
		t.Fatalf("expected VerifyFile to succeed")
	}
	if VerifyFile(testPath, "wrongsha", int64(len(content))) {
		t.Fatalf("expected wrong sha to fail")
	}
	if VerifyFile(testPath, shaStr, int64(len(content)+1)) {
		t.Fatalf("expected wrong size to fail")
	}
	if VerifyFile(filepath.Join(tmpDir, "nonexistent"), shaStr, int64(len(content))) {
		t.Fatalf("expected nonexistent file to fail")
	}
}

func TestDownloadFileAtomic(t *testing.T) {
	content := []byte("mock model weights data")
	h := sha256.Sum256(content)
	shaStr := hex.EncodeToString(h[:])

	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write(content)
	}))
	defer srv.Close()

	tmpDir := t.TempDir()
	m := ModelFile{
		Name:   "test_model.onnx",
		URL:    srv.URL,
		SHA256: shaStr,
		Size:   int64(len(content)),
	}

	err := downloadFile(context.Background(), tmpDir, m)
	if err != nil {
		t.Fatalf("downloadFile failed: %v", err)
	}

	dest := filepath.Join(tmpDir, m.Name)
	if !VerifyFile(dest, shaStr, int64(len(content))) {
		t.Fatalf("downloaded file failed verification")
	}
}
