package shortcode

import (
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"testing"
)

func TestExpandSourceWholeFile(t *testing.T) {
	contentDir := t.TempDir()
	writeSnippet(t, contentDir, "demo.go", "package main\n\nfunc main() {}\n")

	out, err := ExpandSource(`{{< source "/snippets/demo.go" >}}`, contentDir)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	checks := []string{
		`<figure class="source-snippet">`,
		`<figcaption>/snippets/demo.go</figcaption>`,
		`package`,
		`func`,
	}
	for _, check := range checks {
		if !strings.Contains(out, check) {
			t.Fatalf("expected output to contain %q", check)
		}
	}
}

func TestExpandSourceWithRangeTitleLangAndHighlights(t *testing.T) {
	contentDir := t.TempDir()
	writeSnippet(t, contentDir, "demo.go", "package main\n\nfunc add(a, b int) int {\n\treturn a + b\n}\n")

	out, err := ExpandSource(`{{< source "/snippets/demo.go" lines="3-4" lang=go title="adder" hl="4" >}}`, contentDir)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !strings.Contains(out, `<figcaption>adder</figcaption>`) {
		t.Fatalf("expected custom title in output: %s", out)
	}
	if !strings.Contains(out, `func`) || !strings.Contains(out, `return`) {
		t.Fatalf("expected ranged content in output: %s", out)
	}
	if strings.Contains(out, `package`) {
		t.Fatalf("did not expect omitted lines in output: %s", out)
	}
	if !regexp.MustCompile(`display:flex; background-color:#f2ddb4[^>]*>.*?>\s*4</span>`).MatchString(out) {
		t.Fatalf("expected highlighted line wrapper in output: %s", out)
	}
}

func TestExpandSourceRangeHighlightsUseOriginalFileLineNumbers(t *testing.T) {
	contentDir := t.TempDir()
	writeSnippet(t, contentDir, "demo.go", strings.Join([]string{
		"line 1",
		"line 2",
		"line 3",
		"line 4",
		"line 5",
		"line 6",
		"line 7",
		"line 8",
		"line 9",
		"line 10",
		"line 11",
		"line 12",
	}, "\n")+"\n")

	out, err := ExpandSource(`{{< source "/snippets/demo.go" lines="5-11" hl="7-9" >}}`, contentDir)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}

	for _, line := range []string{"7", "8", "9"} {
		pattern := `display:flex; background-color:#f2ddb4[^>]*>.*?>\s*` + line + `</span>`
		if !regexp.MustCompile(pattern).MatchString(out) {
			t.Fatalf("expected line %s to be highlighted: %s", line, out)
		}
	}

	for _, line := range []string{"5", "6", "10", "11"} {
		pattern := `display:flex; background-color:#f2ddb4[^>]*>.*?>\s*` + line + `</span>`
		if regexp.MustCompile(pattern).MatchString(out) {
			t.Fatalf("did not expect line %s to be highlighted: %s", line, out)
		}
	}
	if strings.Contains(out, `line 4`) || strings.Contains(out, `line 12`) {
		t.Fatalf("did not expect lines outside selected range in output: %s", out)
	}
}

func TestExpandSourceInvalidPathTraversal(t *testing.T) {
	contentDir := t.TempDir()
	_, err := ExpandSource(`{{< source "/snippets/../secrets.txt" >}}`, contentDir)
	if err == nil {
		t.Fatal("expected path traversal error")
	}
}

func TestExpandSourceMissingFile(t *testing.T) {
	contentDir := t.TempDir()
	_, err := ExpandSource(`{{< source "/snippets/missing.go" >}}`, contentDir)
	if err == nil {
		t.Fatal("expected missing file error")
	}
}

func TestExpandSourceInvalidRange(t *testing.T) {
	contentDir := t.TempDir()
	writeSnippet(t, contentDir, "demo.go", "one\ntwo\nthree\n")

	_, err := ExpandSource(`{{< source "/snippets/demo.go" lines="4-5" >}}`, contentDir)
	if err == nil {
		t.Fatal("expected invalid range error")
	}
}

func TestExpandSourceInvalidHighlightRange(t *testing.T) {
	contentDir := t.TempDir()
	writeSnippet(t, contentDir, "demo.go", "one\ntwo\nthree\n")

	_, err := ExpandSource(`{{< source "/snippets/demo.go" lines="2-3" hl="1" >}}`, contentDir)
	if err == nil {
		t.Fatal("expected invalid highlight range error")
	}
}

func TestExpandShortcodesSupportsAsciinemaAndSource(t *testing.T) {
	contentDir := t.TempDir()
	writeSnippet(t, contentDir, "demo.go", "package main\n")

	in := `before
{{< asciinema "/casts/demo.cast" theme=none >}}
{{< source "/snippets/demo.go" lines="1" >}}
after`
	out, err := Expand(in, contentDir)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	checks := []string{
		`class="asciinema-player"`,
		`class="source-snippet"`,
		`/snippets/demo.go:1-1`,
	}
	for _, check := range checks {
		if !strings.Contains(out, check) {
			t.Fatalf("expected output to contain %q", check)
		}
	}
}

func TestExpandSourceSkipsInlineCodeSpans(t *testing.T) {
	contentDir := t.TempDir()
	writeSnippet(t, contentDir, "demo.go", "package main\n")

	in := "Use `{{< source \"/snippets/demo.go\" >}}` here."
	out, err := ExpandSource(in, contentDir)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if out != in {
		t.Fatalf("expected inline shortcode example to remain literal:\n%s", out)
	}
}

func TestExpandSkipsShortcodesInsideMarkdownCodeAndExpandsOutside(t *testing.T) {
	contentDir := t.TempDir()
	writeSnippet(t, contentDir, "demo.go", "package main\n")

	in := "before\n```md\n{{< source \"/snippets/demo.go\" >}}\n{{< asciinema \"/casts/demo.cast\" theme=none >}}\n```\n\nUse `{{< source \"/snippets/demo.go\" >}}` inline.\n\n{{< source \"/snippets/demo.go\" lines=\"1\" >}}\n{{< asciinema \"/casts/demo.cast\" theme=none >}}\nafter"
	out, err := Expand(in, contentDir)
	if err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
	if !strings.Contains(out, "```md\n{{< source \"/snippets/demo.go\" >}}\n{{< asciinema \"/casts/demo.cast\" theme=none >}}\n```") {
		t.Fatalf("expected fenced shortcode examples to remain literal:\n%s", out)
	}
	if !strings.Contains(out, "`{{< source \"/snippets/demo.go\" >}}`") {
		t.Fatalf("expected inline shortcode example to remain literal:\n%s", out)
	}
	for _, check := range []string{`class="source-snippet"`, `class="asciinema-player"`} {
		if !strings.Contains(out, check) {
			t.Fatalf("expected output to contain %q: %s", check, out)
		}
	}
}

func writeSnippet(t *testing.T, contentDir, name, body string) {
	t.Helper()
	dir := filepath.Join(contentDir, "snippets")
	if err := os.MkdirAll(dir, 0o755); err != nil {
		t.Fatalf("mkdir snippets: %v", err)
	}
	if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
		t.Fatalf("write snippet: %v", err)
	}
}
