package shortcode

import (
	"bytes"
	"fmt"
	"html"
	"os"
	"path"
	"path/filepath"
	"regexp"
	"strconv"
	"strings"

	"github.com/alecthomas/chroma/v2"
	chromahtml "github.com/alecthomas/chroma/v2/formatters/html"
	"github.com/alecthomas/chroma/v2/lexers"
	"github.com/alecthomas/chroma/v2/styles"
)

var sourceShortcodePattern = regexp.MustCompile(`\{\{<\s*source\s+([^>]+?)\s*>\}\}`)

const sourceLineHighlightStyle = "bg:#f2ddb4"

func ExpandSource(markdown, contentDir string) (string, error) {
	return expandOutsideMarkdownCode(markdown, sourceShortcodePattern, func(full string, match []string) (string, error) {
		if len(match) != 2 {
			return "", fmt.Errorf("invalid source shortcode: %s", full)
		}
		return renderSource(strings.TrimSpace(match[1]), contentDir)
	})
}

func renderSource(args, contentDir string) (string, error) {
	tokens, err := splitArgs(args)
	if err != nil {
		return "", fmt.Errorf("parse source args: %w", err)
	}
	if len(tokens) < 1 {
		return "", fmt.Errorf("source shortcode requires snippet path")
	}

	snippetPath, fullPath, err := resolveSnippetPath(contentDir, strings.Trim(tokens[0], `"`))
	if err != nil {
		return "", err
	}

	lang := ""
	title := ""
	linesValue := ""
	highlightValue := ""

	for _, t := range tokens[1:] {
		parts := strings.SplitN(t, "=", 2)
		if len(parts) != 2 {
			continue
		}
		k := strings.TrimSpace(parts[0])
		v := strings.Trim(strings.TrimSpace(parts[1]), `"`)
		switch k {
		case "lang":
			lang = v
		case "title":
			title = v
		case "lines":
			linesValue = v
		case "hl":
			highlightValue = v
		}
	}

	src, err := os.ReadFile(fullPath)
	if err != nil {
		return "", fmt.Errorf("read source snippet %s: %w", snippetPath, err)
	}

	lines := splitSourceLines(string(src))
	if len(lines) == 0 {
		lines = []string{""}
	}
	startLine, endLine, err := parseLineRange(linesValue, len(lines))
	if err != nil {
		return "", fmt.Errorf("invalid source lines for %s: %w", snippetPath, err)
	}
	highlightLines, err := parseHighlightLines(highlightValue, startLine, endLine)
	if err != nil {
		return "", fmt.Errorf("invalid highlight lines for %s: %w", snippetPath, err)
	}

	selected := strings.Join(lines[startLine-1:endLine], "\n")
	if endLine == len(lines) && strings.HasSuffix(normalizeNewlines(string(src)), "\n") {
		selected += "\n"
	}

	rendered, err := renderHighlightedSource(snippetPath, selected, lang, highlightLines, startLine)
	if err != nil {
		return "", err
	}

	label := title
	if label == "" {
		label = snippetPath
		if linesValue != "" {
			label = fmt.Sprintf("%s:%d-%d", label, startLine, endLine)
		}
	}

	return fmt.Sprintf(
		`<figure class="source-snippet"><figcaption>%s</figcaption>%s</figure>`,
		html.EscapeString(label),
		rendered,
	), nil
}

func resolveSnippetPath(contentDir, shortcodePath string) (string, string, error) {
	if shortcodePath == "" {
		return "", "", fmt.Errorf("source snippet path is empty")
	}
	if containsControlChar(shortcodePath) {
		return "", "", fmt.Errorf("source snippet path contains control characters")
	}

	cleanPath := path.Clean("/" + strings.TrimPrefix(shortcodePath, "/"))
	if !strings.HasPrefix(cleanPath, "/snippets/") {
		return "", "", fmt.Errorf("source snippet path must stay under /snippets")
	}

	fullPath := filepath.Clean(filepath.Join(contentDir, filepath.FromSlash(strings.TrimPrefix(cleanPath, "/"))))
	baseDir := filepath.Clean(filepath.Join(contentDir, "snippets"))
	if fullPath != baseDir && !strings.HasPrefix(fullPath, baseDir+string(filepath.Separator)) {
		return "", "", fmt.Errorf("source snippet path escapes content/snippets")
	}

	return cleanPath, fullPath, nil
}

func splitSourceLines(src string) []string {
	normalized := normalizeNewlines(src)
	if normalized == "" {
		return nil
	}
	lines := strings.Split(normalized, "\n")
	if lines[len(lines)-1] == "" {
		lines = lines[:len(lines)-1]
	}
	return lines
}

func normalizeNewlines(src string) string {
	src = strings.ReplaceAll(src, "\r\n", "\n")
	return strings.ReplaceAll(src, "\r", "\n")
}

func parseLineRange(v string, total int) (int, int, error) {
	if total <= 0 {
		return 1, 1, nil
	}
	if v == "" {
		return 1, total, nil
	}
	if strings.Contains(v, "-") {
		parts := strings.SplitN(v, "-", 2)
		if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
			return 0, 0, fmt.Errorf("expected N or N-M")
		}
		start, err := strconv.Atoi(parts[0])
		if err != nil {
			return 0, 0, fmt.Errorf("invalid start line %q", parts[0])
		}
		end, err := strconv.Atoi(parts[1])
		if err != nil {
			return 0, 0, fmt.Errorf("invalid end line %q", parts[1])
		}
		if start < 1 || end < 1 || end < start {
			return 0, 0, fmt.Errorf("range must be ascending and 1-based")
		}
		if end > total {
			return 0, 0, fmt.Errorf("range %d-%d exceeds %d lines", start, end, total)
		}
		return start, end, nil
	}

	line, err := strconv.Atoi(v)
	if err != nil || line < 1 {
		return 0, 0, fmt.Errorf("line must be a positive integer")
	}
	if line > total {
		return 0, 0, fmt.Errorf("line %d exceeds %d lines", line, total)
	}
	return line, line, nil
}

func parseHighlightLines(v string, startLine, endLine int) ([][2]int, error) {
	if strings.TrimSpace(v) == "" {
		return nil, nil
	}
	items := strings.Split(v, ",")
	ranges := make([][2]int, 0, len(items))
	for _, item := range items {
		item = strings.TrimSpace(item)
		if item == "" {
			return nil, fmt.Errorf("empty highlight line entry")
		}
		start, end, err := parseLineRange(item, endLine)
		if err != nil {
			return nil, err
		}
		if start < startLine || end > endLine {
			return nil, fmt.Errorf("highlight range %d-%d falls outside displayed lines %d-%d", start, end, startLine, endLine)
		}
		ranges = append(ranges, [2]int{start, end})
	}
	return ranges, nil
}

func renderHighlightedSource(snippetPath, src, lang string, highlightLines [][2]int, startLine int) (string, error) {
	lexer := pickLexer(snippetPath, lang)
	iterator, err := lexer.Tokenise(nil, src)
	if err != nil {
		return "", fmt.Errorf("highlight source %s: %w", snippetPath, err)
	}

	style := sourceHighlightStyle()
	formatter := chromahtml.New(
		chromahtml.WithClasses(false),
		chromahtml.WithLineNumbers(true),
		chromahtml.BaseLineNumber(startLine),
		chromahtml.HighlightLines(highlightLines),
	)

	var buf bytes.Buffer
	if err := formatter.Format(&buf, style, iterator); err != nil {
		return "", fmt.Errorf("format highlighted source %s: %w", snippetPath, err)
	}
	return buf.String(), nil
}

func sourceHighlightStyle() *chroma.Style {
	base := styles.Get("github")
	if base == nil {
		base = styles.Fallback
	}
	builder := base.Builder().Add(chroma.LineHighlight, sourceLineHighlightStyle)
	style, err := builder.Build()
	if err != nil {
		return base
	}
	return style
}

func pickLexer(snippetPath, lang string) chroma.Lexer {
	if lang != "" {
		if lexer := lexers.Get(lang); lexer != nil {
			return chroma.Coalesce(lexer)
		}
	}
	if lexer := lexers.Match(snippetPath); lexer != nil {
		return chroma.Coalesce(lexer)
	}
	return chroma.Coalesce(lexers.Fallback)
}
