// Package highlight kleurt een bronbestand per regel.
package highlight

import (
	"html"
	"path"
	"strings"
)

// Lines geeft per regel HTML. Tekst uit het bestand is geëscaped.
func Lines(filename, src string) []string {
	lang := langOf(filename)
	inBlock := false
	raw := strings.Split(src, "\n")
	if len(raw) > 0 && raw[len(raw)-1] == "" && strings.HasSuffix(src, "\n") {
		raw = raw[:len(raw)-1]
	}
	out := make([]string, 0, len(raw))
	for _, line := range raw {
		var htmlLine string
		htmlLine, inBlock = paint(lang, line, inBlock)
		out = append(out, htmlLine)
	}
	return out
}

func langOf(filename string) string {
	switch strings.ToLower(path.Ext(filename)) {
	case ".go":
		return "go"
	case ".js", ".mjs":
		return "js"
	case ".ts":
		return "ts"
	case ".py":
		return "py"
	case ".rs":
		return "rs"
	case ".c", ".h", ".cpp":
		return "c"
	case ".rb":
		return "rb"
	case ".sh", ".bash":
		return "sh"
	case ".yml", ".yaml":
		return "yml"
	case ".toml":
		return "toml"
	case ".json":
		return "json"
	case ".css":
		return "css"
	case ".sql":
		return "sql"
	case ".html", ".xml":
		return "html"
	case ".md":
		return "md"
	default:
		base := strings.ToLower(path.Base(filename))
		if base == "dockerfile" || strings.HasSuffix(base, ".dockerfile") {
			return "sh"
		}
		return ""
	}
}

var keywords = map[string]map[string]bool{
	"go":  words("func package import return if else for var const type struct map range switch case default break continue go defer select chan interface nil true false"),
	"js":  words("function return if else for var const let class new this null undefined true false import export async await"),
	"ts":  words("function return if else for var const let class new this null undefined true false import export async await type interface"),
	"py":  words("def class return if else elif for while import from as none true false and or not in with lambda try except"),
	"rs":  words("fn let mut pub struct enum impl trait use mod return if else for while match loop true false self"),
	"c":   words("if else for while return struct enum typedef void int char const static"),
	"rb":  words("def class end if else elsif do module require return nil true false"),
	"sh":  words("if then else fi for while do done case esac function return"),
	"sql": words("select from where insert update delete create table join left right on as and or not null"),
}

func words(s string) map[string]bool {
	m := map[string]bool{}
	for _, w := range strings.Fields(s) {
		m[w] = true
	}
	return m
}

func hashComment(lang string) bool {
	switch lang {
	case "py", "sh", "yml", "toml", "rb":
		return true
	}
	return false
}

func blockComment(lang string) bool {
	switch lang {
	case "go", "js", "ts", "rs", "c", "css", "sql":
		return true
	}
	return false
}

func paint(lang, line string, inBlock bool) (string, bool) {
	var b strings.Builder
	i := 0
	for i < len(line) {
		rest := line[i:]
		if inBlock {
			end := strings.Index(rest, "*/")
			if end < 0 {
				b.WriteString(`<span class="hl-c">`)
				b.WriteString(html.EscapeString(rest))
				b.WriteString("</span>")
				return b.String(), true
			}
			b.WriteString(`<span class="hl-c">`)
			b.WriteString(html.EscapeString(rest[:end+2]))
			b.WriteString("</span>")
			i += end + 2
			inBlock = false
			continue
		}
		if strings.HasPrefix(rest, "//") || (hashComment(lang) && strings.HasPrefix(rest, "#")) || (lang == "sql" && strings.HasPrefix(rest, "--")) {
			b.WriteString(`<span class="hl-c">`)
			b.WriteString(html.EscapeString(rest))
			b.WriteString("</span>")
			return b.String(), false
		}
		if blockComment(lang) && strings.HasPrefix(rest, "/*") {
			inBlock = true
			continue
		}
		if rest[0] == '"' || rest[0] == '\'' || (rest[0] == '`' && lang == "go") {
			q := rest[0]
			j := 1
			for j < len(rest) {
				if rest[j] == '\\' && q != '`' {
					j += 2
					continue
				}
				if rest[j] == q {
					j++
					break
				}
				j++
			}
			if j > len(rest) {
				j = len(rest)
			}
			b.WriteString(`<span class="hl-s">`)
			b.WriteString(html.EscapeString(rest[:j]))
			b.WriteString("</span>")
			i += j
			continue
		}
		if rest[0] >= '0' && rest[0] <= '9' {
			j := 1
			for j < len(rest) && ((rest[j] >= '0' && rest[j] <= '9') || rest[j] == '.') {
				j++
			}
			b.WriteString(`<span class="hl-n">`)
			b.WriteString(html.EscapeString(rest[:j]))
			b.WriteString("</span>")
			i += j
			continue
		}
		if isIdent(rest[0]) {
			j := 1
			for j < len(rest) && (isIdent(rest[j]) || (rest[j] >= '0' && rest[j] <= '9')) {
				j++
			}
			word := rest[:j]
			if keywords[lang][word] {
				b.WriteString(`<span class="hl-k">`)
				b.WriteString(html.EscapeString(word))
				b.WriteString("</span>")
			} else {
				b.WriteString(html.EscapeString(word))
			}
			i += j
			continue
		}
		b.WriteString(html.EscapeString(rest[:1]))
		i++
	}
	return b.String(), inBlock
}

func isIdent(c byte) bool {
	return c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
}
