package preproc

import "testing"

func TestNewPragma(t *testing.T) {
	p := NewPragma()
	if len(p.pragmaSetStack) != 1 {
		t.Errorf("expected initial stack length 1, got %d", len(p.pragmaSetStack))
	}
	if p.GetCurrentPragmaSetIndex() != 0 {
		t.Errorf("expected initial index 0, got %d", p.GetCurrentPragmaSetIndex())
	}
}

func TestAddPragma(t *testing.T) {
	p := NewPragma()

	p.AddPragma("foo", "bar")
	if p.GetCurrentPragmaSetIndex() != 1 {
		t.Errorf("expected index 1 after add, got %d", p.GetCurrentPragmaSetIndex())
	}

	ps := p.GetPragmaSetByIndex(1)
	if ps.GetPragma("foo") != "bar" {
		t.Errorf("expected 'bar', got '%s'", ps.GetPragma("foo"))
	}
}

func TestPragmaImmutability(t *testing.T) {
	p := NewPragma()
	p.AddPragma("x", "1")
	idx1 := p.GetCurrentPragmaSetIndex()

	p.AddPragma("x", "2")
	idx2 := p.GetCurrentPragmaSetIndex()

	ps1 := p.GetPragmaSetByIndex(idx1)
	ps2 := p.GetPragmaSetByIndex(idx2)

	if ps1.GetPragma("x") != "1" {
		t.Errorf("snapshot corrupted: expected '1', got '%s'", ps1.GetPragma("x"))
	}
	if ps2.GetPragma("x") != "2" {
		t.Errorf("expected '2', got '%s'", ps2.GetPragma("x"))
	}
}

func TestGetPragmaMissing(t *testing.T) {
	p := NewPragma()
	ps := p.GetPragmaSetByIndex(0)

	if ps.GetPragma("missing") != "" {
		t.Errorf("expected empty string for missing pragma")
	}
}

func TestGetPragmaWrongIndex(t *testing.T) {
	p := NewPragma()

	defer func() {
		if r := recover(); r == nil {
			t.Errorf("expected panic for index -1")
		}
	}()

	p.GetPragmaSetByIndex(-1)
}

func TestMultiplePragmas(t *testing.T) {
	p := NewPragma()
	p.AddPragma("a", "1")
	p.AddPragma("b", "2")

	ps := p.GetPragmaSetByIndex(p.GetCurrentPragmaSetIndex())

	if ps.GetPragma("a") != "1" {
		t.Errorf("expected 'a'='1'")
	}
	if ps.GetPragma("b") != "2" {
		t.Errorf("expected 'b'='2'")
	}
}
