package pierre

import (
	"fmt"
	"strings"
	"testing"
)

func TestParseGuidelinesFromStringValid(t *testing.T) {
	md := "# Rule One\n\n  - Item A  \n\n# Rule Two\n"
	lines, err := parseGuidelinesFromString(md)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	expected := []string{"# Rule One", "- Item A", "# Rule Two"}
	if got, want := fmt.Sprint(lines), fmt.Sprint(expected); got != want {
		t.Fatalf("expected %v, got %v", expected, lines)
	}
}

func TestParseGuidelinesFromStringEmpty(t *testing.T) {
	md := "\n   \n"
	lines, err := parseGuidelinesFromString(md)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if len(lines) != 0 {
		t.Fatalf("expected empty slice, got %d elements", len(lines))
	}
}

func TestParseGuidelinesFromStringTooManyLines(t *testing.T) {
	// generate 1001 non-empty lines
	var sb strings.Builder
	for i := 0; i < 1001; i++ {
		sb.WriteString(fmt.Sprintf("Line %d\n", i))
	}
	_, err := parseGuidelinesFromString(sb.String())
	if err == nil {
		t.Fatalf("expected error for exceeding line limit, got nil")
	}
}

func TestWithGuidelinesSuccess(t *testing.T) {
	svc := &Service{}
	md := "First line\nSecond line\n"
	if err := svc.WithGuidelines(md); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	expected := []string{"First line", "Second line"}
	if got, want := fmt.Sprint(svc.guidelines), fmt.Sprint(expected); got != want {
		t.Fatalf("expected guidelines %v, got %v", expected, svc.guidelines)
	}
}

func TestWithGuidelinesError(t *testing.T) {
	svc := &Service{guidelines: []string{"old"}}
	var sb strings.Builder
	for i := 0; i < 1001; i++ {
		sb.WriteString("x\n")
	}
	err := svc.WithGuidelines(sb.String())
	if err == nil {
		t.Fatalf("expected error, got nil")
	}
	// ensure old guidelines unchanged
	if len(svc.guidelines) != 1 || svc.guidelines[0] != "old" {
		t.Fatalf("guidelines should remain unchanged on error")
	}
}
