import Foundation

public enum TOMLParser {
    public static func parse(_ source: String) throws -> TOMLDocument {
        try TOMLDocument(parsing: source)
    }
}

struct TOMLSection: Sendable {
    let path: [TOMLPathComponent]
    let insertionOffset: Int
}

private final class ParsedNode {
    enum Content {
        case value(TOMLValue)
        case table([String: ParsedNode])
        case array([ParsedNode])
    }

    var content: Content
    var range: SourceRange
    var keyRange: SourceRange?
    var declared = false
    var dotted = false
    var sealed = false
    var arrayOfTables = false

    init(_ content: Content, range: SourceRange) {
        self.content = content
        self.range = range
    }

    func freeze() -> TOMLNode {
        let value: TOMLValue
        switch content {
        case .value(let scalar): value = scalar
        case .table(let entries): value = .table(entries.mapValues { $0.freeze() })
        case .array(let entries): value = .array(entries.map { $0.freeze() })
        }
        return TOMLNode(value: value, range: range, keyRange: keyRange)
    }
}

struct TOMLReader {
    private let scalars: [Unicode.Scalar]
    private var index = 0
    private var lineStarts = [0]
    private var depth = 0
    private(set) var sections = [TOMLSection(path: [], insertionOffset: 0)]
    private(set) var editableRanges: [[TOMLPathComponent]: SourceRange] = [:]

    init(_ source: String) {
        scalars = Array(source.unicodeScalars)
        for (offset, scalar) in scalars.enumerated() where scalar == "\n" {
            lineStarts.append(offset + 1)
        }
    }

    mutating func parse() throws -> TOMLNode {
        let root = ParsedNode(.table([:]), range: range(0, scalars.count))
        var current = root
        var currentPath: [TOMLPathComponent] = []
        while !atEnd {
            skipSpaces()
            if peek() == "#" { try skipComment() }
            if try consumeNewline() { continue }
            if atEnd { break }
            if peek() == "[" {
                let start = index
                index += 1
                let isArray = consume("[")
                let keys = try parseKeys()
                try expect("]")
                if isArray { try expect("]") }
                (current, currentPath) = try openTable(root, keys: keys, isArray: isArray, start: start)
                try finishLine()
                sections.append(TOMLSection(path: currentPath, insertionOffset: index))
            } else {
                let keys = try parseKeys()
                try expect("=")
                skipSpaces()
                let value = try parseValue()
                try insert(value, keys: keys, into: current)
                recordEditable(value, path: currentPath + keys.map { .key($0.0) })
                try finishLine()
            }
        }
        return root.freeze()
    }

    private var atEnd: Bool { index >= scalars.count }

    private func peek(_ ahead: Int = 0) -> Unicode.Scalar? {
        let position = index + ahead
        return position < scalars.count ? scalars[position] : nil
    }

    private func location(_ offset: Int) -> SourceLocation {
        var low = 0
        var high = lineStarts.count
        while low + 1 < high {
            let middle = (low + high) / 2
            if lineStarts[middle] <= offset { low = middle } else { high = middle }
        }
        return SourceLocation(line: low + 1, column: offset - lineStarts[low] + 1, offset: offset)
    }

    private func range(_ start: Int, _ end: Int) -> SourceRange {
        SourceRange(start: location(start), end: location(end))
    }

    private func error(_ message: String.LocalizationValue, at offset: Int? = nil) -> ConfigDiagnostic {
        ConfigDiagnostic(
            location: location(offset ?? index),
            message: String(localized: message, table: "Parser", bundle: .module)
        )
    }

    private mutating func consume(_ scalar: Unicode.Scalar) -> Bool {
        guard peek() == scalar else { return false }
        index += 1
        return true
    }

    private mutating func expect(_ scalar: Unicode.Scalar) throws {
        guard consume(scalar) else { throw error("Expected `\(String(scalar))` here.") }
    }

    private mutating func skipSpaces() {
        while peek() == " " || peek() == "\t" { index += 1 }
    }

    private mutating func consumeNewline() throws -> Bool {
        if consume("\n") { return true }
        if peek() == "\r" {
            guard peek(1) == "\n" else { throw error("Use a newline or a CRLF pair, not a bare carriage return.") }
            index += 2
            return true
        }
        return false
    }

    private mutating func skipComment() throws {
        while let scalar = peek(), scalar != "\n", scalar != "\r" {
            guard !isForbiddenControl(scalar) else { throw error("Comments cannot contain control characters.") }
            index += 1
        }
    }

    private mutating func finishLine() throws {
        skipSpaces()
        if peek() == "#" { try skipComment() }
        if atEnd { return }
        guard try consumeNewline() else { throw error("Put each assignment or table header on its own line.") }
    }

    private mutating func skipArrayWhitespace() throws {
        while true {
            skipSpaces()
            if peek() == "#" { try skipComment() }
            if try !consumeNewline() { break }
        }
    }

    private func isForbiddenControl(_ scalar: Unicode.Scalar) -> Bool {
        scalar.value < 0x20 && scalar != "\t" || scalar.value == 0x7F
    }

    private func isBareKey(_ scalar: Unicode.Scalar) -> Bool {
        switch scalar.value {
        case 48...57, 65...90, 97...122, 45, 95: true
        default: false
        }
    }

    private mutating func parseKeys() throws -> [(String, SourceRange)] {
        var keys: [(String, SourceRange)] = []
        repeat {
            guard keys.count + depth < 128 else {
                throw error("This value is nested too deeply; use fewer than 128 levels.")
            }
            skipSpaces()
            let start = index
            let key: String
            if peek() == "\"" || peek() == "'" {
                key = try parseString(allowMultiline: false)
            } else {
                while let scalar = peek(), isBareKey(scalar) { index += 1 }
                guard index > start else { throw error("Expected a key, like `gap` or `\"display name\"`.") }
                key = text(start, index)
            }
            keys.append((key, range(start, index)))
            skipSpaces()
        } while consume(".")
        return keys
    }

    private func text(_ start: Int, _ end: Int) -> String {
        String(String.UnicodeScalarView(scalars[start..<end]))
    }

    private mutating func parseValue() throws -> ParsedNode {
        guard depth < 128 else { throw error("This value is nested too deeply; use fewer than 128 levels.") }
        depth += 1
        defer { depth -= 1 }
        let start = index
        let content: ParsedNode.Content
        switch peek() {
        case "\"", "'": content = .value(.string(try parseString(allowMultiline: true)))
        case "[":
            index += 1
            var values: [ParsedNode] = []
            try skipArrayWhitespace()
            if !consume("]") {
                while true {
                    values.append(try parseValue())
                    try skipArrayWhitespace()
                    if consume("]") { break }
                    try expect(",")
                    try skipArrayWhitespace()
                    if consume("]") { break }
                }
            }
            content = .array(values)
        case "{":
            index += 1
            let table = ParsedNode(.table([:]), range: range(start, index))
            skipSpaces()
            if !consume("}") {
                while true {
                    let keys = try parseKeys()
                    try expect("=")
                    skipSpaces()
                    let dottedDepth = keys.count - 1
                    depth += dottedDepth
                    defer { depth -= dottedDepth }
                    try insert(try parseValue(), keys: keys, into: table)
                    skipSpaces()
                    if consume("}") { break }
                    try expect(",")
                    skipSpaces()
                    if peek() == "}" { throw error("Inline tables cannot end with a trailing comma.") }
                }
            }
            table.range = range(start, index)
            table.sealed = true
            return table
        default: content = .value(try parseScalar())
        }
        return ParsedNode(content, range: range(start, index))
    }

    private mutating func parseScalar() throws -> TOMLValue {
        let start = index
        while let scalar = peek(), ![" ", "\t", "\r", "\n", "#", ",", "]", "}"].contains(scalar) {
            index += 1
        }
        let token = text(start, index)
        if token == "true" { return .bool(true) }
        if token == "false" { return .bool(false) }
        if token.range(of: #"^\d{4}-\d{2}-\d{2}|^\d{2}:\d{2}:\d{2}"#, options: .regularExpression) != nil {
            throw error(
                "Dates and times are not supported in Parcel config; quote this value to use it as text.", at: start)
        }
        if ["inf", "+inf", "-inf", "nan", "+nan", "-nan"].contains(token) {
            return .float(token.hasSuffix("nan") ? .nan : (token == "-inf" ? -.infinity : .infinity))
        }
        let patterns: [(String, Int)] = [
            (#"^0x[0-9a-fA-F](?:_?[0-9a-fA-F])*$"#, 16),
            (#"^0o[0-7](?:_?[0-7])*$"#, 8),
            (#"^0b[01](?:_?[01])*$"#, 2),
            (#"^[+-]?(?:0|[1-9](?:_?[0-9])*)$"#, 10),
        ]
        for (pattern, radix) in patterns where token.range(of: pattern, options: .regularExpression) != nil {
            let digits = radix == 10 ? token : String(token.dropFirst(2))
            guard let integer = Int64(digits.replacingOccurrences(of: "_", with: ""), radix: radix) else {
                throw error("This integer is outside the signed 64-bit range.", at: start)
            }
            return .integer(integer)
        }
        let floatPattern =
            #"^[+-]?(?:0|[1-9](?:_?[0-9])*)(?:(?:\.[0-9](?:_?[0-9])*)(?:[eE][+-]?[0-9](?:_?[0-9])*)?|[eE][+-]?[0-9](?:_?[0-9])*)$"#
        if token.range(of: floatPattern, options: .regularExpression) != nil {
            guard let number = Double(token.replacingOccurrences(of: "_", with: "")), number.isFinite else {
                throw error(
                    "This floating-point number is too large; use `inf` only when infinity is intended.", at: start)
            }
            return .float(number)
        }
        throw error("Expected a string, number, boolean, array, or inline table; text needs quotes.", at: start)
    }

    private mutating func parseString(allowMultiline: Bool) throws -> String {
        let start = index
        guard let quote = peek() else { throw error("Expected a quoted string.") }
        index += 1
        let multiline = peek() == quote && peek(1) == quote
        if multiline {
            guard allowMultiline else { throw error("Keys must use single-line strings.", at: start) }
            index += 2
            _ = try consumeNewline()
        }
        var result = String.UnicodeScalarView()
        while let scalar = peek() {
            if scalar == quote {
                if !multiline {
                    index += 1
                    return String(result)
                }
                var count = 0
                while peek(count) == quote { count += 1 }
                if count >= 3 {
                    guard count <= 5 else { throw error("Too many closing quotes; escape quotes inside the string.") }
                    for _ in 3..<count { result.append(quote) }
                    index += count
                    return String(result)
                }
                result.append(scalar)
                index += 1
            } else if scalar == "\\" && quote == "\"" {
                index += 1
                if multiline && [" ", "\t", "\n", "\r"].contains(peek()) {
                    skipSpaces()
                    guard try consumeNewline() else {
                        throw error("A line continuation needs a newline after the backslash.")
                    }
                    while true {
                        skipSpaces()
                        if try !consumeNewline() { break }
                    }
                } else {
                    result.append(try parseEscape())
                }
            } else if scalar == "\n" || scalar == "\r" {
                guard multiline else { throw error("Single-line strings cannot contain a newline.") }
                _ = try consumeNewline()
                result.append("\n")
            } else {
                guard !isForbiddenControl(scalar) else {
                    throw error("Strings cannot contain unescaped control characters.")
                }
                result.append(scalar)
                index += 1
            }
        }
        throw error("This string is missing its closing quote.", at: start)
    }

    private mutating func parseEscape() throws -> Unicode.Scalar {
        let start = index - 1
        guard let scalar = peek() else { throw error("This escape sequence is incomplete.", at: start) }
        index += 1
        switch scalar {
        case "b": return "\u{08}"
        case "t": return "\t"
        case "n": return "\n"
        case "f": return "\u{0C}"
        case "r": return "\r"
        case "\"": return "\""
        case "\\": return "\\"
        case "u", "U":
            let length = scalar == "u" ? 4 : 8
            let digitsStart = index
            for _ in 0..<length {
                guard let next = peek(), next.isASCII,
                    (48...57).contains(next.value) || (65...70).contains(next.value) || (97...102).contains(next.value)
                else { throw error("A Unicode escape needs four or eight hexadecimal digits.", at: start) }
                index += 1
            }
            guard let value = UInt32(text(digitsStart, index), radix: 16), let decoded = Unicode.Scalar(value) else {
                throw error("This Unicode escape is not a valid Unicode scalar.", at: start)
            }
            return decoded
        default: throw error("Unknown escape sequence; use `\\\\` for a literal backslash.", at: start)
        }
    }

    private func duplicate(_ key: String, range: SourceRange, previous: ParsedNode) -> ConfigDiagnostic {
        let first = previous.keyRange?.start ?? previous.range.start
        return ConfigDiagnostic(
            location: range.start,
            message: String(
                localized: "`\(key)` was already defined at line \(first.line), column \(first.column).",
                table: "Parser", bundle: .module
            ), relatedLocation: first
        )
    }

    private func insert(_ value: ParsedNode, keys: [(String, SourceRange)], into table: ParsedNode) throws {
        var current = table
        for (position, pair) in keys.enumerated() {
            let (key, keyRange) = pair
            guard case .table(var entries) = current.content, !current.sealed else {
                throw error("A dotted key cannot extend a value or an inline table.", at: keyRange.start.offset)
            }
            if position == keys.count - 1 {
                if let previous = entries[key] { throw duplicate(key, range: keyRange, previous: previous) }
                value.keyRange = keyRange
                entries[key] = value
                current.content = .table(entries)
            } else if let next = entries[key] {
                guard !next.declared else {
                    throw error("A dotted key cannot redefine a table declared by a header.", at: keyRange.start.offset)
                }
                next.dotted = true
                current = next
            } else {
                let next = ParsedNode(.table([:]), range: keyRange)
                next.keyRange = keyRange
                next.dotted = true
                entries[key] = next
                current.content = .table(entries)
                current = next
            }
        }
    }

    private func openTable(
        _ root: ParsedNode, keys: [(String, SourceRange)], isArray: Bool, start: Int
    ) throws -> (ParsedNode, [TOMLPathComponent]) {
        var current = root
        var path: [TOMLPathComponent] = []
        for (position, pair) in keys.enumerated() {
            let (key, keyRange) = pair
            let last = position == keys.count - 1
            guard case .table(var entries) = current.content, !current.sealed else {
                throw error("A table header cannot extend a value or an inline table.", at: keyRange.start.offset)
            }
            path.append(.key(key))
            let next: ParsedNode
            if let existing = entries[key] {
                next = existing
            } else {
                next = ParsedNode(isArray && last ? .array([]) : .table([:]), range: keyRange)
                next.keyRange = keyRange
                next.arrayOfTables = isArray && last
                entries[key] = next
                current.content = .table(entries)
            }
            if next.arrayOfTables, case .array(var elements) = next.content {
                if last && isArray {
                    let element = ParsedNode(.table([:]), range: range(start, index))
                    element.declared = true
                    element.keyRange = keyRange
                    elements.append(element)
                    next.content = .array(elements)
                } else if last {
                    throw duplicate(key, range: keyRange, previous: next)
                }
                guard let element = elements.last else {
                    throw error("This array of tables has no current table.", at: keyRange.start.offset)
                }
                path.append(.index(elements.count - 1))
                current = element
            } else {
                guard case .table = next.content, !next.sealed else {
                    throw duplicate(key, range: keyRange, previous: next)
                }
                if last {
                    guard !isArray, !next.declared, !next.dotted else {
                        throw duplicate(key, range: keyRange, previous: next)
                    }
                    next.declared = true
                    next.range = range(start, index)
                    next.keyRange = keyRange
                }
                current = next
            }
        }
        return (current, path)
    }

    private mutating func recordEditable(_ node: ParsedNode, path: [TOMLPathComponent]) {
        if !node.dotted { editableRanges[path] = node.range }
        switch node.content {
        case .table(let entries):
            for (key, child) in entries { recordEditable(child, path: path + [.key(key)]) }
        case .array(let entries):
            for (index, child) in entries.enumerated() { recordEditable(child, path: path + [.index(index)]) }
        case .value: break
        }
    }
}
