import Foundation enum IntakeLocationMatcher { static func match(_ hint: String?, locations: [Place], defaultID: UUID?) -> UUID? { let current = locations.first { $0.id == defaultID } guard let hint, !hint.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return current?.id } let literal = key(hint) guard !literal.isEmpty else { return nil } let withoutPrefix = stripPrefix(literal) let terms = [literal, withoutPrefix, stripSuffix(withoutPrefix)].filter { !$0.isEmpty } for term in terms { let paths = locations.filter { key($0.path) == term } if !paths.isEmpty { return unique(paths, within: current) } } for term in terms { let names = locations.filter { key($0.name) == term } if !names.isEmpty { return unique(names, within: current) } } for term in terms { let trailingPaths = locations.filter { place in let components = place.path.components(separatedBy: " / ") return components.indices.dropFirst().contains { key(components[$0...].joined()) == term } } if !trailingPaths.isEmpty { return unique(trailingPaths, within: current) } } return nil } private static func unique(_ matching: [Place], within current: Place?) -> UUID? { if matching.count == 1 { return matching.first?.id } guard let current else { return nil } let local = matching.filter { $0.id == current.id || $0.path.hasPrefix(current.path + " / ") } return local.count == 1 ? local.first?.id : nil } private static func key(_ value: String) -> String { value.folding(options: [.caseInsensitive, .widthInsensitive], locale: Locale(identifier: "zh-CN")) .filter { !$0.isWhitespace && !$0.isPunctuation } } private static func stripPrefix(_ value: String) -> String { guard let prefix = ["放在", "放到", "收进", "在", "到"].first(where: { value.hasPrefix($0) }) else { return value } return String(value.dropFirst(prefix.count)) } private static func stripSuffix(_ value: String) -> String { guard let suffix = ["里面了", "里边了", "里了", "内了", "里面", "里边", "里", "内", "了"] .first(where: { value.hasSuffix($0) }) else { return value } return String(value.dropLast(suffix.count)) } }