package web
import (
"html"
"html/template"
"net/url"
"regexp"
"strconv"
"strings"
"amadan.net/oficina/base/internal/equipo"
)
// linkRE finds a Markdown link [label](target), or a bare http(s) URL.
var linkRE = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|https?://[^\s<>()\[\]"']+`)
// richText is an Assistant's line as HTML, in the little Markdown it may
// write (plan decision D16): runs of "- " or "* " lines are a bulleted
// list, runs of "1. " or "1) " lines (1 to 3 digits) a numbered one, and
// every other line is text with its newlines (the one next to a list
// goes). In text and list items, a Markdown link or bare URL is a link
// only when it goes to an http(s) address, and between links **x** is
// bold, *x* and _x_ italic. Every other character is escaped: raw HTML,
// relative paths and any other Markdown stay text. The panel's script does
// the same (ask.js, rich). Its line breaks are read as a page reads them
// (\r\n and \r are \n, and a NUL goes), so the two draw the same.
func richText(text string) template.HTML { return richMarkdown(text, false) }
// personText is the person's own message as HTML: richText's little
// Markdown, but stricter about emphasis (strictEmphasis), since people
// write arithmetic, file names and code: 2*3*4, x**2 and __init__.py stay
// as written. ask.js (rich, strict) and the app (PersonMarkdown) do the
// same.
func personText(text string) template.HTML { return richMarkdown(text, true) }
func richMarkdown(text string, strict bool) template.HTML { return markdown(text, strict, true) }
// lookupSpace is the whitespace a lookup's answer ends an address at,
// spelled out so Go, ask.js (with its u flag) and the app's ICU read it
// alike: ASCII's, and Unicode's spaces and line breaks.
const lookupSpace = `\t\n\f\r \x{00a0}\x{1680}\x{2000}-\x{200a}\x{2028}\x{2029}\x{202f}\x{205f}\x{3000}`
// mdLinkRE is a Markdown link, [label](target), in a lookup's answer;
// plainLinkRE is linkRE for one, with lookupSpace for its whitespace.
var (
mdLinkRE = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()` + lookupSpace + `]{1,1000})\)`)
plainLinkRE = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()` + lookupSpace + `]{1,1000})\)|https?://[^` + lookupSpace + `<>()\[\]"']+`)
)
// lookupMarkdown is a lookup's answer as HTML: personText's Markdown
// (lists, and bold and italics at word boundaries) with no links at all,
// since the only links under a reply are the sources Equipo recorded
// (spec 2026-11-26-assistant-abilities ยง4.6). A Markdown link shows as
// its words; a bare URL or an autolink stays as text. ask.js
// (lookupMarkdown) and the app (LookupMarkdown) do the same.
func lookupMarkdown(text string) template.HTML {
return markdown(mdLinkRE.ReplaceAllString(asPageReads.Replace(text), "$1"), true, false)
}
// markdown is richMarkdown, with links drawn only when links is set
// (otherwise every address is text).
func markdown(text string, strict, links bool) template.HTML {
var b strings.Builder
lines := strings.Split(asPageReads.Replace(text), "\n")
for i := 0; i < len(lines); {
kind, n, _ := listLine(lines[i])
if kind == "" {
j := i + 1
for j < len(lines) && !isListLine(lines[j]) {
j++
}
inline(&b, strings.Join(lines[i:j], "\n"), strict, links)
i = j
continue
}
if kind == "ol" && n != 1 {
b.WriteString(`
`)
} else {
b.WriteString("<" + kind + ">")
}
for ; i < len(lines); i++ {
k, _, item := listLine(lines[i])
if k != kind {
break
}
b.WriteString("- ")
inline(&b, item, strict, links)
b.WriteString("
")
}
b.WriteString("" + kind + ">")
}
return template.HTML(b.String())
}
var asPageReads = strings.NewReplacer("\r\n", "\n", "\r", "\n", "\x00", "")
// numberRE is a numbered list line's start: 1 to 3 digits, "." or ")",
// a space.
var numberRE = regexp.MustCompile(`^(\d{1,3})[.)] `)
// listLine is line's list ("ul" or "ol", else ""), its number for "ol",
// and the item after the marker, which is never empty.
func listLine(line string) (kind string, n int, item string) {
if len(line) > 2 && (line[0] == '-' || line[0] == '*') && line[1] == ' ' {
return "ul", 0, line[2:]
}
if m := numberRE.FindStringSubmatch(line); m != nil && len(line) > len(m[0]) {
n, _ := strconv.Atoi(m[1])
return "ol", n, line[len(m[0]):]
}
return "", 0, ""
}
func isListLine(line string) bool { k, _, _ := listLine(line); return k != "" }
// inline writes text with its safe links, and bold and italics between
// them. Without links, each address is written as text, untouched by
// emphasis.
func inline(b *strings.Builder, text string, strict, links bool) {
emphasis := emphasis
if strict {
emphasis = strictEmphasis
}
re := linkRE
if !links {
re = plainLinkRE
}
last := 0
for _, m := range re.FindAllStringSubmatchIndex(text, -1) {
end, label, target := m[1], "", ""
if m[2] >= 0 {
label, target = text[m[2]:m[3]], text[m[4]:m[5]]
} else {
target = strings.TrimRight(text[m[0]:m[1]], ".,;:!?")
end, label = m[0]+len(target), target
}
if !links {
// An address is text, whatever it is: no URL check decides
// how it is drawn.
emphasis(b, text[last:m[0]])
b.WriteString(html.EscapeString(text[m[0]:end]))
last = end
continue
}
href := equipo.WebURL(target)
if href == "" {
continue
}
emphasis(b, text[last:m[0]])
b.WriteString(`` + html.EscapeString(label) + ``)
last = end
}
emphasis(b, text[last:])
}
// emphasis writes text escaped, with **x** as and *x* or _x_ as
// : x is the text up to the next same marker, not empty, on one line,
// and neither starting nor ending with a space; an _ also needs no word
// character just outside it, so snake_case stays as it is. Nothing nests.
func emphasis(b *strings.Builder, text string) {
last := 0
for i := 0; i < len(text); {
c := text[i]
if c == '*' && strings.HasPrefix(text[i+1:], "*") {
if j := strings.Index(text[i+2:], "**"); j >= 0 && emphasized(text[i+2:i+2+j]) {
b.WriteString(html.EscapeString(text[last:i]) + "" + html.EscapeString(text[i+2:i+2+j]) + "")
i += j + 4
last = i
continue
}
}
if c == '*' || c == '_' && (i == 0 || !wordByte(text[i-1])) {
j := strings.IndexByte(text[i+1:], c)
if j >= 0 && emphasized(text[i+1:i+1+j]) && (c == '*' || i+2+j == len(text) || !wordByte(text[i+2+j])) {
b.WriteString(html.EscapeString(text[last:i]) + "" + html.EscapeString(text[i+1:i+1+j]) + "")
i += j + 2
last = i
continue
}
}
i++
}
b.WriteString(html.EscapeString(text[last:]))
}
// strictEmphasis is emphasis for the person's words: **x** and *x* or _x_
// only at word boundaries. A run of markers opens only at the start or
// after a character that is no word's (a space, punctuation), closes only
// at the end or before one, and is exactly one * or _, or two *: so
// 2*3*4, a*b + c*d, x**2 + y**2 and __init__.py stay as written. x is as
// in emphasis. Each run looks only as far as the next of its marker, so it
// is linear.
func strictEmphasis(b *strings.Builder, text string) {
last := 0
for i := 0; i < len(text); {
c := text[i]
if c != '*' && c != '_' {
i++
continue
}
run := markerRun(text, i)
if (i == 0 || !wordByte(text[i-1])) && (run == 1 || run == 2 && c == '*') {
from := i + run
if k := strings.IndexByte(text[from:], c); k >= 0 {
j := from + k
end := j + markerRun(text, j)
if x := text[from:j]; end-j == run && emphasized(x) && (end == len(text) || !wordByte(text[end])) {
tag := "em"
if run == 2 {
tag = "strong"
}
b.WriteString(html.EscapeString(text[last:i]) + "<" + tag + ">" + html.EscapeString(x) + "" + tag + ">")
i, last = end, end
continue
}
}
}
i += run
}
b.WriteString(html.EscapeString(text[last:]))
}
// markerRun is how many of text[i] follow one another from i.
func markerRun(text string, i int) int {
n := 1
for i+n < len(text) && text[i+n] == text[i] {
n++
}
return n
}
// emphasized is whether x may be bold or italic: not empty, on one line,
// with no space at either end.
func emphasized(x string) bool {
return x != "" && !strings.Contains(x, "\n") && !space(x[0]) && !space(x[len(x)-1])
}
func space(c byte) bool { return c == ' ' || c == '\t' }
// wordByte is whether c is part of a word: an ASCII letter, digit or _, or
// any byte of a character beyond ASCII (ask.js sees the same in UTF-16).
func wordByte(c byte) bool {
return c >= 0x80 || c == '_' || '0' <= c && c <= '9' || 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z'
}
// Rich is an Assistant's line with its links (richText), for templates.
func (v askView) Rich(text string) template.HTML { return richText(text) }
// sourceHost is u's host name as a source line shows it after the
// source's title, without a leading "www.". ask.js has the same
// (sourceHost).
func sourceHost(u string) string {
p, err := url.Parse(u)
if err != nil {
return ""
}
return strings.TrimPrefix(strings.ToLower(p.Hostname()), "www.")
}
// RichPerson is the person's own message (personText), for templates.
func (v askView) RichPerson(text string) template.HTML { return personText(text) }