package isobuilder

import (
	"os"
	"os/exec"
	"path/filepath"
	"testing"
)

func TestBuildFromDirectory(t *testing.T) {
	srcDir := "/tmp/build_iso/xcdrom"
	isoPath := "/tmp/dicom_purego_test.iso"

	// Check if source exists (might need to be created first)
	if _, err := os.Stat(srcDir); os.IsNotExist(err) {
		t.Skipf("source dir %s does not exist, skipping", srcDir)
	}

	// Clean up any previous test ISO
	os.Remove(isoPath)

	// Build ISO using pure Go
	err := BuildFromDirectory(srcDir, isoPath, "DICOM")
	if err != nil {
		t.Fatalf("BuildFromDirectory failed: %v", err)
	}
	defer os.Remove(isoPath)

	// Verify ISO file exists and has reasonable size
	info, err := os.Stat(isoPath)
	if err != nil {
		t.Fatalf("cannot stat ISO: %v", err)
	}
	if info.Size() == 0 {
		t.Fatal("ISO is empty")
	}
	t.Logf("ISO created: %s (%.2f MB)", isoPath, float64(info.Size())/1024/1024)

	// Verify it's a valid ISO 9660 using file command
	cmd := exec.Command("file", isoPath)
	output, _ := cmd.Output()
	t.Logf("file type: %s", string(output))

	// Verify contents using isoinfo
	cmd = exec.Command("isoinfo", "-l", "-i", isoPath)
	output, _ = cmd.Output()
	t.Logf("ISO listing:\n%s", string(output))
}

func TestDirSize(t *testing.T) {
	// Create a temp dir with known file sizes
	tmpDir := t.TempDir()

	// Create a 1KB file
	f1 := filepath.Join(tmpDir, "file1.bin")
	os.WriteFile(f1, make([]byte, 1024), 0644)

	// Create a subdirectory with a 2KB file
	subDir := filepath.Join(tmpDir, "subdir")
	os.Mkdir(subDir, 0755)
	f2 := filepath.Join(subDir, "file2.bin")
	os.WriteFile(f2, make([]byte, 2048), 0644)

	size, err := dirSize(tmpDir)
	if err != nil {
		t.Fatalf("dirSize failed: %v", err)
	}

	// Expected: (1024 + 2048) = 3072 + 10% = 3379,
	// minimum 10MB = 10485760, round up to 2048: 10485760
	// Since 3072 < 10MB, should be 10485760 (already aligned)
	if size < 10*1024*1024 {
		t.Fatalf("expected minimum 10MB, got %d", size)
	}
	if size%2048 != 0 {
		t.Fatalf("expected 2048-aligned, got %d", size)
	}
	t.Logf("dirSize(%s) = %d bytes (%.2f MB)", tmpDir, size, float64(size)/1024/1024)
}
