import Foundation #if os(macOS) import AppKit #elseif os(iOS) import UIKit #endif /// A rich paste (a web page, Docs, Mail) as the Markdown the chat draws: /// bold (**x**), italics (*x*), links ([text](url), http(s) only, as /// BaseJSON.webURL), bullet and numbered lists (nested by indent), headings /// (# x), and line breaks and paragraphs. Everything else is its text. Nil /// when the paste formats nothing, or is mostly code (a monospace font, or /// pre, code, tt, samp, kbd; RTF in a fixed-pitch font), so a plain paste /// or code stays exactly as copied. HTML is only tokenised here and walked /// (nothing loads or runs): elements deeper than 32 are flattened, the /// walk stops once the Markdown passes the composer's 16,000 characters, /// and more than 2 MB of HTML is left plain. RTF is read by Foundation, /// which loads nothing either. ask.js's pasteMarkdown is the same walk /// (keep them in step: the samples in /// internal/browsertest/testdata/paste.json check both). enum PasteMarkdown { static let maxDepth = 32, maxOut = 16_000, maxHTML = 2_000_000 static func fromHTML(_ html: String) -> String? { guard html.utf16.count <= maxHTML else { return nil } var walker = Walker() // (A NUL marks a
's place in the walk's output, as a page's
        // parser never leaves one in text.)
        return walker.markdown(HTMLTree.parse(html.replacingOccurrences(of: "\0", with: "")))
    }

    /// A clipboard's HTML bytes as text: UTF-8, or UTF-16 with its mark.
    static func html(_ data: Data) -> String? {
        if data.starts(with: [0xFF, 0xFE]) || data.starts(with: [0xFE, 0xFF]) { return String(data: data, encoding: .utf16) }
        return String(data: data, encoding: .utf8)
    }

    static func fromRTF(_ data: Data) -> String? {
        guard let text = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil) else { return nil }
        return fromAttributed(text)
    }

    /// An attributed string's paragraphs as lines (lists by their text
    /// lists), its runs bold, italic or linked by their attributes: the
    /// same tree HTML makes, so the same walk.
    static func fromAttributed(_ text: NSAttributedString) -> String? {
        var walker = Walker()
        return walker.markdown(HTMLTree.from(text))
    }
}

/// Just enough HTML: elements with their attributes, and text. Tags that
/// are never closed close with their parent; a stray end tag is dropped.
struct HTMLTree: Equatable {
    var tag = ""                // "" is text
    var attributes: [String: String] = [:]
    var text = ""
    var children: [HTMLTree] = []

    static let void: Set = ["br", "img", "hr", "input", "meta", "link", "area", "base", "col", "embed", "source", "track", "wbr", "param"]
    static let raw: Set = ["script", "style", "textarea", "title", "template", "noscript", "iframe", "xmp", "plaintext"]
    /// What a new block closes when it opens, as a page would.
    static let closesP: Set = ["p", "div", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "table", "blockquote", "section", "article", "header", "footer", "hr", "dl", "form"]

    static func parse(_ html: String) -> HTMLTree {
        let s = Array(html.unicodeScalars)
        var stack = [HTMLTree(tag: "body")]
        // Elements opened past the depth cap: not in the tree (their text
        // and line breaks go to the deepest one that is; a block is a line
        // of its own, a cell a space, and what the walk skips is skipped),
        // but their end tags still match them.
        enum Drop { case inline, block, cell, skip }
        var dropped: [(name: String, kind: Drop)] = []
        var skipping = 0
        func mark(_ tag: String) { stack[stack.count - 1].children.append(HTMLTree(tag: tag)) }
        var at = 0
        func appendText(_ t: String) {
            guard !t.isEmpty, skipping == 0 else { return }
            stack[stack.count - 1].children.append(HTMLTree(text: MarkdownEntities.link(t)))
        }
        func close(_ index: Int) {
            while stack.count > index {
                let done = stack.removeLast()
                stack[stack.count - 1].children.append(done)
            }
        }
        func open(_ name: String) -> Int? { stack.lastIndex { $0.tag == name } }
        var text = ""
        while at < s.count {
            guard s[at] == "<" else { text.unicodeScalars.append(s[at]); at += 1; continue }
            // A comment, doctype or processing instruction: skipped.
            if at + 3 < s.count, s[at + 1] == "!", s[at + 2] == "-", s[at + 3] == "-" {
                appendText(text); text = ""
                var end = at + 4
                while end + 2 < s.count, !(s[end] == "-" && s[end + 1] == "-" && s[end + 2] == ">") { end += 1 }
                at = min(s.count, end + 3)
                continue
            }
            if at + 1 < s.count, s[at + 1] == "!" || s[at + 1] == "?" {
                appendText(text); text = ""
                while at < s.count, s[at] != ">" { at += 1 }
                at += 1
                continue
            }
            let closing = at + 1 < s.count && s[at + 1] == "/"
            var cursor = at + (closing ? 2 : 1)
            var name = ""
            while cursor < s.count, s[cursor].properties.isAlphabetic || ("0"..."9").contains(s[cursor]) || s[cursor] == "-" || s[cursor] == ":" {
                name.unicodeScalars.append(s[cursor]); cursor += 1
            }
            guard !name.isEmpty else { text.unicodeScalars.append(s[at]); at += 1; continue }
            name = name.lowercased()
            // The attributes, to the tag's end.
            var attributes: [String: String] = [:]
            var selfClosing = false
            while cursor < s.count, s[cursor] != ">" {
                if s[cursor] == "/" { selfClosing = true; cursor += 1; continue }
                if s[cursor].properties.isWhitespace { cursor += 1; continue }
                selfClosing = false
                var key = ""
                while cursor < s.count, !s[cursor].properties.isWhitespace, !"=>/".unicodeScalars.contains(s[cursor]) {
                    key.unicodeScalars.append(s[cursor]); cursor += 1
                }
                while cursor < s.count, s[cursor].properties.isWhitespace { cursor += 1 }
                var value = ""
                if cursor < s.count, s[cursor] == "=" {
                    cursor += 1
                    while cursor < s.count, s[cursor].properties.isWhitespace { cursor += 1 }
                    if cursor < s.count, s[cursor] == "\"" || s[cursor] == "'" {
                        let quote = s[cursor]; cursor += 1
                        while cursor < s.count, s[cursor] != quote { value.unicodeScalars.append(s[cursor]); cursor += 1 }
                        cursor += 1
                    } else {
                        while cursor < s.count, !s[cursor].properties.isWhitespace, s[cursor] != ">" { value.unicodeScalars.append(s[cursor]); cursor += 1 }
                    }
                }
                if key.isEmpty { cursor += 1; continue }
                let k = key.lowercased()
                if attributes[k] == nil { attributes[k] = MarkdownEntities.link(value) }
            }
            at = min(s.count, cursor + 1)
            appendText(text); text = ""
            if closing {
                if dropped.last?.name == name {
                    switch dropped.removeLast().kind {
                    case .skip: skipping -= 1
                    case .block: mark(Walker.line)
                    case .cell: mark(Walker.cell)
                    case .inline: break
                    }
                } else if let index = open(name), index > 0 { close(index) }
                continue
            }
            if closesP.contains(name), let p = open("p"), !(stack[(p + 1)...].contains { $0.tag == "li" || $0.tag == "td" || $0.tag == "th" }) { close(p) }
            if name == "li", let li = open("li"), !stack[(li + 1)...].contains(where: { $0.tag == "ul" || $0.tag == "ol" }) { close(li) }
            let element = HTMLTree(tag: name, attributes: attributes)
            if raw.contains(name) {
                // Its content is text to its end tag; none of it is kept
                // (the walk skips all of these).
                var end = at
                let closer = Array("" { at += 1 }
                at += 1
                continue
            }
            if skipping > 0 {
                if !void.contains(name), !selfClosing { dropped.append((name, .skip)); skipping += 1 }
            } else if void.contains(name) || selfClosing {
                stack[stack.count - 1].children.append(element)
            } else if stack.count > PasteMarkdown.maxDepth {
                let kind: Drop = Walker.skip.contains(name) ? .skip : Walker.blocks.contains(name) ? .block : name == "td" || name == "th" ? .cell : .inline
                if kind == .skip { skipping += 1 }
                if kind == .block { mark(Walker.line) }
                dropped.append((name, kind))
            } else {
                stack.append(element)
            }
        }
        appendText(text)
        close(1)
        return stack[0]
    }

    /// The tree an attributed string's paragraphs and runs make.
    static func from(_ text: NSAttributedString) -> HTMLTree {
        var body = HTMLTree(tag: "body")
        // The open lists: each the list node path from body.
        var lists: [(ordered: Bool, node: HTMLTree)] = []
        func closeLists(to depth: Int) {
            while lists.count > depth {
                let done = lists.removeLast().node
                if lists.isEmpty {
                    body.children.append(done)
                } else {
                    lists[lists.count - 1].node.children.append(done)
                }
            }
        }
        let string = text.string as NSString
        string.enumerateSubstrings(in: NSRange(location: 0, length: string.length), options: [.byParagraphs, .substringNotRequired]) { _, content, _, _ in
            let style = content.length > 0 ? text.attribute(.paragraphStyle, at: content.location, effectiveRange: nil) as? NSParagraphStyle : nil
            let textLists = style?.textLists ?? []
            var line = HTMLTree(tag: textLists.isEmpty ? "div" : "li")
            var runsFrom = content.location
            if !textLists.isEmpty, let marker = Self.listMarker.firstMatch(in: text.string, range: content) {
                // A list's marker is in the text ("\t•\t", "\t1.\t"): it goes.
                runsFrom += marker.range.length
            }
            if runsFrom < NSMaxRange(content) {
                text.enumerateAttributes(in: NSRange(location: runsFrom, length: NSMaxRange(content) - runsFrom)) { attributes, run, _ in
                    var node = HTMLTree(text: string.substring(with: run).replacingOccurrences(of: "\0", with: ""))
                    if let link = attributes[.link] {
                        let href = (link as? URL)?.absoluteString ?? (link as? String) ?? ""
                        node = HTMLTree(tag: "a", attributes: ["href": href], children: [node])
                    }
                    let (bold, italic, mono) = traits(attributes)
                    if italic { node = HTMLTree(tag: "i", children: [node]) }
                    if bold { node = HTMLTree(tag: "b", children: [node]) }
                    if mono { node = HTMLTree(tag: "code", children: [node]) }
                    line.children.append(node)
                }
            } else if textLists.isEmpty {
                line.children.append(HTMLTree(tag: "br"))
            }
            // The paragraph's lists, outermost first.
            let depth = textLists.count
            var shared = 0
            while shared < min(depth, lists.count), lists[shared].ordered == ordered(textLists[shared]) { shared += 1 }
            closeLists(to: shared)
            while lists.count < depth {
                let ordered = ordered(textLists[lists.count])
                lists.append((ordered, HTMLTree(tag: ordered ? "ol" : "ul")))
            }
            if depth == 0 { body.children.append(line) } else { lists[lists.count - 1].node.children.append(line) }
        }
        closeLists(to: 0)
        return body
    }

    private static let listMarker = try! NSRegularExpression(pattern: #"\G\t?[^\t\n]{0,12}\t"#)

    private static func ordered(_ list: NSTextList) -> Bool {
        !["disc", "circle", "square", "box", "check", "diamond", "hyphen"].contains { list.markerFormat.rawValue.contains($0) }
    }

    private static func traits(_ attributes: [NSAttributedString.Key: Any]) -> (bold: Bool, italic: Bool, mono: Bool) {
        #if os(macOS)
        guard let font = attributes[.font] as? NSFont else { return (false, false, false) }
        let t = font.fontDescriptor.symbolicTraits
        return (t.contains(.bold), t.contains(.italic), t.contains(.monoSpace) || font.isFixedPitch)
        #elseif os(iOS)
        guard let font = attributes[.font] as? UIFont else { return (false, false, false) }
        let t = font.fontDescriptor.symbolicTraits
        return (t.contains(.traitBold), t.contains(.traitItalic), t.contains(.traitMonoSpace))
        #else
        return (false, false, false)
        #endif
    }
}

/// ask.js's pasteMarkdown walk, line for line.
private struct Walker {
    struct Run { var text: String; var bold: Bool; var italic: Bool; var href: String }
    struct Style { var bold = false, italic = false, href = "", heading = false, mono = false }
    static let code: Set = ["code", "tt", "samp", "kbd"]
    static let blocks = lines.union(["p", "li", "ul", "ol", "h1", "h2", "h3", "h4", "h5", "h6", "pre"])
    /// Marks HTMLTree.parse leaves for blocks and cells past the depth
    /// cap (no tag a page can write starts with "_").
    static let line = "_line", cell = "_cell"
    static let raw: Set = ["script", "style", "textarea", "title", "template", "noscript", "iframe"]
    static let monoFont = try! NSRegularExpression(pattern: "monospace|menlo|monaco|consolas|courier|sf ?mono|fira (code|mono)|jetbrains|source code|cascadia|ubuntu mono|dejavu sans mono|roboto mono|plex mono|andale mono|lucida console", options: .caseInsensitive)
    final class List { let ordered: Bool; var n: Int; let indent: String; var inner: String
        init(ordered: Bool, n: Int, indent: String) { self.ordered = ordered; self.n = n; self.indent = indent; inner = indent }
    }
    static let skip: Set = ["script", "style", "head", "title", "template", "noscript", "iframe", "object", "embed", "svg", "math", "canvas", "video", "audio", "picture", "img", "button", "select", "input", "textarea"]
    static let lines: Set = ["div", "section", "article", "header", "footer", "main", "nav", "aside", "blockquote", "figure", "figcaption", "address", "center", "details", "summary", "form", "fieldset", "table", "thead", "tbody", "tfoot", "tr", "caption", "dl", "dt", "dd", "hr"]

    var out = ""
    var runs: [Run] = []
    var open = false
    var marker: String?
    var indent = ""
    var formatted = false
    var lists: [List] = []
    /// Characters of text (not spaces), and how many of them are code's.
    var chars = 0, mono = 0
    /// Each 
's text, standing in the output as NUL, its number, NUL
    /// until the clean-up is done: its spaces and blank lines are the
    /// code's.
    var verbatim: [String] = []

    mutating func markdown(_ tree: HTMLTree) -> String? {
        walk(tree, Style(), depth: -1)
        flush()
        guard formatted, mono * 2 <= chars else { return nil }
        let trimmed = out.components(separatedBy: "\n").map { line in
            var line = line
            while line.last == " " || line.last == "\t" { line.removeLast() }
            return line
        }.joined(separator: "\n")
        var result = trimmed.replacingOccurrences(of: #"\n{3,}"#, with: "\n\n", options: .regularExpression)
        while result.first == "\n" { result.removeFirst() }
        while result.last == "\n" { result.removeLast() }
        for (n, code) in verbatim.enumerated().reversed() { result = result.replacingOccurrences(of: "\0\(n)\0", with: code) }
        return result
    }

    mutating func flush() {
        var s = inline(runs)
        runs = []
        while s.first == " " { s.removeFirst() }
        guard !s.isEmpty else { return }
        if open { out += s } else {
            out += (marker ?? indent) + s
            if marker != nil { formatted = true }
        }
        marker = nil
        open = true
    }

    mutating func ensure(_ n: Int) {
        flush()
        open = false
        guard !out.isEmpty else { return }
        var have = 0
        for c in out.reversed() { if c == "\n" { have += 1 } else { break } }
        while have < n { out += "\n"; have += 1 }
    }

    mutating func walk(_ node: HTMLTree, _ st: Style, depth: Int) {
        if out.utf16.count > PasteMarkdown.maxOut { return }
        if node.tag.isEmpty {
            let counted = node.text.unicodeScalars.reduce(0) { $0 + ($1.properties.isWhitespace ? 0 : $1.utf16.count) }
            chars += counted
            if st.mono { mono += counted }
            var t = node.text.replacingOccurrences(of: "[ \\t\\n\\r\\f\u{00a0}]+", with: " ", options: .regularExpression)
            // One space between words, whichever side of a tag it was.
            if t.first == " ", runs.last?.text.last == " " { t.removeFirst() }
            if !t.isEmpty { runs.append(Run(text: t, bold: st.heading ? false : st.bold, italic: st.heading ? false : st.italic, href: st.href)) }
            return
        }
        let tag = node.tag
        if tag == "br" {
            flush()
            if !out.isEmpty { out += "\n"; open = false }
            return
        }
        // (The body is depth -1; its children 0. HTMLTree.parse never makes
        // anything deeper than the cap, and marks what it flattened.)
        if tag == Self.line { ensure(1); return }
        if tag == Self.cell { runs.append(Run(text: " ", bold: false, italic: false, href: "")); return }
        if Self.skip.contains(tag) { return }
        var next = st
        if tag == "b" || tag == "strong" { next.bold = true }
        if tag == "i" || tag == "em" { next.italic = true }
        if Self.code.contains(tag) { next.mono = true }
        let style = node.attributes["style"] ?? ""
        if let weight = Self.declared(style, "font-weight") {
            next.bold = weight.range(of: "^(bold|bolder|[6-9]00)$", options: [.regularExpression, .caseInsensitive]) != nil
        }
        if let slant = Self.declared(style, "font-style") {
            next.italic = slant.range(of: "^(italic|oblique)", options: [.regularExpression, .caseInsensitive]) != nil
        }
        if let family = Self.declared(style, "font-family") {
            next.mono = Self.monoFont.firstMatch(in: family, range: NSRange(family.startIndex..., in: family)) != nil
        }
        if tag == "a", st.href.isEmpty { next.href = Self.link(node.attributes["href"] ?? "") }
        func children(_ w: inout Walker) { for c in node.children { w.walk(c, next, depth: depth + 1) } }

        if tag.count == 2, tag.first == "h", let level = Int(String(tag.last!)), (1...6).contains(level) {
            ensure(2)
            marker = String(repeating: "#", count: level) + " "
            next.heading = true
            let before = formatted
            children(&self)
            flush()
            if marker != nil { marker = nil; formatted = before }
            ensure(2)
            return
        }
        if tag == "ul" || tag == "ol" {
            let top = lists.isEmpty
            let parent = lists.last
            ensure(top ? 2 : 1)
            let start = Int(node.attributes["start"]?.trimmingCharacters(in: .whitespaces) ?? "")
            lists.append(List(ordered: tag == "ol", n: tag == "ol" ? max(0, start ?? 1) : 0, indent: parent?.inner ?? indent))
            let saved = indent
            children(&self)
            lists.removeLast()
            indent = saved
            ensure(top ? 2 : 1)
            return
        }
        if tag == "li" {
            ensure(1)
            let list = lists.last ?? List(ordered: false, n: 0, indent: "")
            let m = list.ordered ? "\(list.n). " : "- "
            if list.ordered { list.n += 1 }
            marker = list.indent + m
            list.inner = list.indent + String(repeating: " ", count: m.count)
            let saved = indent
            indent = list.inner
            children(&self)
            flush()
            marker = nil
            indent = saved
            ensure(1)
            return
        }
        if tag == "p" {
            if !lists.isEmpty {
                flush()
                if open { out += "\n"; open = false }
                children(&self)
                return
            }
            ensure(2); children(&self); ensure(2)
            return
        }
        if tag == "pre" {
            // Verbatim, as a fenced code block longer than any run of
            // backticks in it.
            var code = ""
            func read(_ n: HTMLTree) {
                if n.tag.isEmpty { code += n.text } else if n.tag == "br" { code += "\n" } else if !Self.skip.contains(n.tag) { n.children.forEach(read) }
            }
            read(node)
            code = code.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
            // A page drops the line break just after 
.
            if code.hasPrefix("\n") { code.removeFirst() }
            if code.hasSuffix("\n") { code.removeLast() }
            let counted = code.unicodeScalars.reduce(0) { $0 + ($1.properties.isWhitespace ? 0 : $1.utf16.count) }
            chars += counted
            mono += counted
            guard !code.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
            var longest = 0, run = 0
            for c in code { run = c == "`" ? run + 1 : 0; longest = max(longest, run) }
            let fence = String(repeating: "`", count: max(3, longest + 1))
            ensure(2)
            out += fence + "\n\0\(verbatim.count)\0\n" + fence
            verbatim.append(code)
            formatted = true
            ensure(2)
            return
        }
        if Self.lines.contains(tag) {
            ensure(1); children(&self); ensure(1)
            return
        }
        if tag == "td" || tag == "th" {
            children(&self)
            runs.append(Run(text: " ", bold: false, italic: false, href: ""))
            return
        }
        children(&self)
    }

    /// A line's runs as Markdown: neighbours alike are one run, and a run's
    /// outer spaces stand outside its marks.
    mutating func inline(_ rs: [Run]) -> String {
        var merged: [Run] = []
        for r in rs {
            if let last = merged.last, last.href == r.href, !r.href.isEmpty || (last.bold == r.bold && last.italic == r.italic) {
                merged[merged.count - 1].text += r.text
            } else {
                merged.append(r)
            }
        }
        var s = ""
        for r in merged {
            let lead = String(r.text.prefix { $0 == " " })
            let rest = r.text.dropFirst(lead.count)
            let trail = String(rest.reversed().prefix { $0 == " " })
            let core = String(rest.dropLast(trail.count))
            if core.isEmpty { s += r.text; continue }
            if !r.href.isEmpty {
                let label = core.replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "")
                let href = r.href.replacingOccurrences(of: "(", with: "%28").replacingOccurrences(of: ")", with: "%29")
                s += lead + (label == r.href ? href : label.utf16.count > 300 ? "\(label) (\(href))" : "[\(label)](\(href))") + trail
                formatted = true
            } else if r.bold || r.italic {
                let mark = r.bold ? "**" : "*"
                s += lead + mark + core + mark + trail
                formatted = true
            } else {
                s += r.text
            }
        }
        while s.last == " " { s.removeLast() }
        return s
    }

    /// A declaration's value in a style attribute (never
    /// mso-bidi-font-weight and the like).
    static func declared(_ style: String, _ name: String) -> String? {
        guard let re = try? NSRegularExpression(pattern: "(?:^|;)\\s*\(name)\\s*:\\s*([^;]*)", options: .caseInsensitive),
              let m = re.firstMatch(in: style, range: NSRange(style.startIndex..., in: style)),
              let r = Range(m.range(at: 1), in: style) else { return nil }
        return style[r].replacingOccurrences(of: #"!\s*important\s*$"#, with: "", options: [.regularExpression, .caseInsensitive]).trimmingCharacters(in: .whitespaces)
    }

    /// An href as a page reads it (spaces at its ends go, tabs and line
    /// breaks in it go, other spaces are escaped), if it is http(s).
    static func link(_ href: String) -> String {
        let cleaned = href.trimmingCharacters(in: .whitespacesAndNewlines).filter { $0 != "\t" && $0 != "\n" && $0 != "\r" }
        guard let url = URL(string: cleaned, encodingInvalidCharacters: true) else { return "" }
        return BaseJSON.webURL(url.absoluteString)?.absoluteString ?? ""
    }
}