import Foundation import InkspringSchedule /// Keep link placement independent of the writing provider's output. enum XIdeaDraft { static let linkWritingInstructions = """ For each distinct URL in ideaLinks, return a linkCallsToAction array entry with url (the exact supplied URL) and text. Write one short sentence that tells readers what they will find and what to do, in the author's voice. Use the brief and URL as evidence. Do not make up details about the destination. For an app homepage, invite people to try or download the app. For an article or guide, invite people to read it and say what they will learn if that is supported by the brief. Keep the text under 180 characters and exclude URLs and Markdown. Inkspring will attach each exact URL to its reply. """ static func links(in text: String) -> [String] { matches(in: text).map(\.address) } static func separate(_ opening: String, replies: [String] = [], suppliedLinks: [String], linkCopy: [[String: String]] = [], long: Bool = false) throws -> (text: String, format: String) { let found = matches(in: opening) let clean = removingLinks(from: opening, matches: found) guard !clean.isEmpty, !clean.contains("\0"), !clean.contains(XThreadText.separator) else { throw WorkspaceError("The generated X opening needs some text. Try again with a little more detail.") } var writtenReplies: [String] = [] var bareReplyLinks: [String] = [] for reply in replies { let found = matches(in: reply) let copy = removingLinks(from: reply, matches: found) let label = copy.lowercased().trimmingCharacters(in: .punctuationCharacters.union(.whitespacesAndNewlines)) if !found.isEmpty, label.isEmpty || ["link", "links", "source", "sources", "url", "urls"].contains(label) { bareReplyLinks += found.map(\.address) } else { writtenReplies.append(reply) } } var seen = Set(writtenReplies.flatMap { links(in: $0) }) let missing = (suppliedLinks + found.map(\.address) + bareReplyLinks).filter { seen.insert($0).inserted } var actions: [String: String] = [:] for entry in linkCopy { guard let url = entry["url"], let text = entry["text"], actions[url] == nil else { continue } let copy = text.split(whereSeparator: \.isWhitespace).joined(separator: " ") guard copy.contains(where: \.isLetter), !copy.contains("\0"), !copy.contains("