TitleOptimizationService.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. import Foundation
  2. protocol TitleOptimizationServiceProtocol: Sendable {
  3. func optimizeTitles(from draft: TitleDraft) async throws -> TitleOptimizationResult
  4. }
  5. enum TitleOptimizationError: LocalizedError {
  6. case emptyTopic
  7. case emptySubreddit
  8. case emptyTitle
  9. var errorDescription: String? {
  10. switch self {
  11. case .emptyTopic: "Enter a topic or keywords to guide title generation."
  12. case .emptySubreddit: "Enter a subreddit to tailor titles for that community."
  13. case .emptyTitle: "Enter a title to optimize, or provide a topic to generate from scratch."
  14. }
  15. }
  16. }
  17. struct MockTitleOptimizationService: TitleOptimizationServiceProtocol {
  18. func optimizeTitles(from draft: TitleDraft) async throws -> TitleOptimizationResult {
  19. guard !draft.subreddit.trimmingCharacters(in: .whitespaces).isEmpty else {
  20. throw TitleOptimizationError.emptySubreddit
  21. }
  22. guard !draft.topic.trimmingCharacters(in: .whitespaces).isEmpty else {
  23. throw TitleOptimizationError.emptyTopic
  24. }
  25. let hasTitle = !draft.originalTitle.trimmingCharacters(in: .whitespaces).isEmpty
  26. if !hasTitle {
  27. throw TitleOptimizationError.emptyTitle
  28. }
  29. try await Task.sleep(for: .milliseconds(900))
  30. let subreddit = draft.subreddit.replacingOccurrences(of: "r/", with: "")
  31. let topic = draft.topic.trimmingCharacters(in: .whitespaces)
  32. let original = draft.originalTitle.trimmingCharacters(in: .whitespaces)
  33. let analysis = analyzeTitle(original, goal: draft.titleGoal)
  34. let variants = makeVariants(
  35. original: original,
  36. topic: topic,
  37. subreddit: subreddit,
  38. tone: draft.tone,
  39. goal: draft.titleGoal,
  40. count: draft.variantCount.rawValue
  41. )
  42. return TitleOptimizationResult(analysis: analysis, variants: variants)
  43. }
  44. private func analyzeTitle(_ title: String, goal: TitleGoal) -> TitleAnalysis {
  45. let length = title.count
  46. let lengthScore = scoreLength(length)
  47. let engagementScore = scoreEngagement(title, goal: goal)
  48. let clarityScore = scoreClarity(title)
  49. let overall = (lengthScore + engagementScore + clarityScore) / 3
  50. let suggestions = makeSuggestions(title: title, length: length, goal: goal)
  51. return TitleAnalysis(
  52. overallScore: overall,
  53. lengthScore: lengthScore,
  54. engagementScore: engagementScore,
  55. clarityScore: clarityScore,
  56. suggestions: suggestions
  57. )
  58. }
  59. private func scoreLength(_ length: Int) -> Int {
  60. switch length {
  61. case 0: 0
  62. case 1...50: 95
  63. case 51...80: 85
  64. case 81...120: 70
  65. case 121...200: 50
  66. case 201...300: 30
  67. default: 10
  68. }
  69. }
  70. private func scoreEngagement(_ title: String, goal: TitleGoal) -> Int {
  71. var score = 50
  72. let lower = title.lowercased()
  73. if title.contains("?") { score += 10 }
  74. if title.range(of: #"\d+"#, options: .regularExpression) != nil { score += 8 }
  75. if lower.contains("how") || lower.contains("why") || lower.contains("what") { score += 6 }
  76. if lower.contains("you") || lower.contains("your") { score += 5 }
  77. if title == title.uppercased() && title.count > 5 { score -= 15 }
  78. switch goal {
  79. case .question where !title.contains("?"): score -= 10
  80. case .listicle where title.range(of: #"\d+"#, options: .regularExpression) == nil: score -= 8
  81. case .curiosity where !lower.contains("secret") && !lower.contains("nobody") && !lower.contains("actually"): score -= 3
  82. default: break
  83. }
  84. return min(100, max(0, score))
  85. }
  86. private func scoreClarity(_ title: String) -> Int {
  87. var score = 70
  88. let words = title.split(separator: " ").count
  89. if words >= 4 && words <= 12 { score += 15 }
  90. if words < 3 { score -= 20 }
  91. if words > 20 { score -= 15 }
  92. if title.contains(" ") { score -= 5 }
  93. if title.hasPrefix(" ") || title.hasSuffix(" ") { score -= 10 }
  94. return min(100, max(0, score))
  95. }
  96. private func makeSuggestions(title: String, length: Int, goal: TitleGoal) -> [String] {
  97. var tips: [String] = []
  98. if length > 120 {
  99. tips.append("Shorten to under 80 characters for better mobile visibility.")
  100. } else if length < 20 {
  101. tips.append("Add more context — very short titles can feel vague in feeds.")
  102. }
  103. if !title.contains("?") && goal == .question {
  104. tips.append("Reframe as a question to invite comments.")
  105. }
  106. if title.range(of: #"\d+"#, options: .regularExpression) == nil && goal == .listicle {
  107. tips.append("Include a number (e.g. \"5 tips\") for listicle-style engagement.")
  108. }
  109. let lower = title.lowercased()
  110. if goal == .curiosity && !lower.contains("?") {
  111. tips.append("Add a curiosity hook — hint at a surprising outcome.")
  112. }
  113. if tips.isEmpty {
  114. tips.append("Strong base title — try variants with different hooks below.")
  115. }
  116. return tips
  117. }
  118. private func makeVariants(
  119. original: String,
  120. topic: String,
  121. subreddit: String,
  122. tone: PostTone,
  123. goal: TitleGoal,
  124. count: Int
  125. ) -> [TitleVariant] {
  126. let templates = variantTemplates(
  127. original: original,
  128. topic: topic,
  129. subreddit: subreddit,
  130. tone: tone,
  131. goal: goal
  132. )
  133. return Array(templates.prefix(count)).enumerated().map { index, template in
  134. TitleVariant(
  135. title: template.title,
  136. score: template.score - index * 2,
  137. reasoning: template.reasoning
  138. )
  139. }
  140. }
  141. private func variantTemplates(
  142. original: String,
  143. topic: String,
  144. subreddit: String,
  145. tone: PostTone,
  146. goal: TitleGoal
  147. ) -> [(title: String, score: Int, reasoning: String)] {
  148. let base = original.isEmpty ? topic : original
  149. var results: [(title: String, score: Int, reasoning: String)] = []
  150. switch goal {
  151. case .curiosity:
  152. results = [
  153. ("The \(topic) trick nobody on r/\(subreddit) talks about", 92, "Curiosity gap with community reference"),
  154. ("I tried \(base) for 30 days — here's what actually happened", 89, "Personal experiment hook"),
  155. ("Why \(topic) is quietly changing everything (and most people miss it)", 87, "Insider knowledge angle"),
  156. ("\(base) — am I the only one who noticed this?", 84, "Relatability + intrigue"),
  157. ("What r/\(subreddit) taught me about \(topic) that I wish I knew sooner", 82, "Community wisdom framing"),
  158. ("The uncomfortable truth about \(topic)", 80, "Bold curiosity opener"),
  159. ("\(base): a deep dive you didn't know you needed", 78, "Value promise"),
  160. ("This \(topic) approach changed my mind completely", 76, "Transformation narrative"),
  161. ]
  162. case .question:
  163. results = [
  164. ("What's your experience with \(topic)?", 91, "Direct community question"),
  165. ("Am I wrong about \(base)?", 88, "Invites debate and replies"),
  166. ("How do you approach \(topic) on r/\(subreddit)?", 86, "Subreddit-specific ask"),
  167. ("Is \(topic) actually worth it in 2026?", 84, "Timely relevance question"),
  168. ("Anyone else struggling with \(base)?", 82, "Shared struggle hook"),
  169. ("What's the best \(topic) advice you've ever received?", 80, "Experience-sharing prompt"),
  170. ("\(base) — what am I missing here?", 78, "Humble knowledge seeker"),
  171. ("Hot take or common knowledge: \(topic)?", 76, "Opinion solicitation"),
  172. ]
  173. case .listicle:
  174. results = [
  175. ("7 \(topic) tips that actually work on r/\(subreddit)", 93, "Numbered list with community anchor"),
  176. ("5 mistakes everyone makes with \(base)", 90, "Problem-awareness listicle"),
  177. ("3 reasons \(topic) is underrated right now", 87, "Concise numbered hook"),
  178. ("10 things I learned about \(topic) the hard way", 85, "Lessons-learned format"),
  179. ("The top 5 \(topic) resources you need in 2026", 83, "Resource roundup angle"),
  180. ("\(base): 4 key takeaways from my experience", 81, "Summary-style list"),
  181. ("6 signs you're ready for \(topic)", 79, "Checklist engagement"),
  182. ("8 \(topic) hacks r/\(subreddit) swears by", 77, "Community-endorsed list"),
  183. ]
  184. case .emotional:
  185. results = [
  186. ("\(base) hit me harder than I expected", 91, "Emotional vulnerability"),
  187. ("I wasn't ready for what \(topic) taught me", 88, "Personal revelation"),
  188. ("This \(topic) moment changed everything for me", 86, "Transformation story"),
  189. ("Honestly, \(base) has been on my mind lately", 84, "Authentic confession"),
  190. ("The \(topic) journey nobody prepares you for", 82, "Empathy-driven framing"),
  191. ("Why \(base) still keeps me up at night", 80, "Emotional intensity"),
  192. ("\(topic) — a love letter to r/\(subreddit)", 78, "Community appreciation"),
  193. ("I finally understand \(base) and it's bittersweet", 76, "Reflective tone"),
  194. ]
  195. case .direct:
  196. results = [
  197. ("\(base) — a complete guide for r/\(subreddit)", 92, "Clear value proposition"),
  198. ("Everything you need to know about \(topic)", 89, "Comprehensive promise"),
  199. ("\(topic): what works, what doesn't, and why", 87, "Balanced direct framing"),
  200. ("My honest take on \(base)", 85, "Straightforward opinion"),
  201. ("\(topic) explained simply", 83, "Accessibility focus"),
  202. ("The definitive \(base) breakdown", 81, "Authority positioning"),
  203. ("\(topic) for beginners — start here", 79, "Audience targeting"),
  204. ("\(base): facts, not hype", 77, "No-nonsense angle"),
  205. ]
  206. case .provocative:
  207. results = [
  208. ("Unpopular opinion: \(base) is overrated", 93, "Classic debate starter"),
  209. ("\(topic) is a scam and here's why", 90, "Strong contrarian hook"),
  210. ("Hot take: r/\(subreddit) is wrong about \(topic)", 87, "Community challenge"),
  211. ("Stop doing \(base) — seriously", 85, "Command attention"),
  212. ("\(topic) culture has gone too far", 83, "Cultural critique"),
  213. ("I'll say it: \(base) isn't that impressive", 81, "Mild controversy"),
  214. ("Why everyone is sleeping on the real \(topic) issue", 79, "Contrarian insight"),
  215. ("\(base) — fight me", 77, "Maximum engagement bait"),
  216. ]
  217. }
  218. if tone == .humorous {
  219. results = results.map { variant in
  220. (title: variant.title + " 😅", score: variant.score - 3, reasoning: variant.reasoning + " (humorous tone)")
  221. }
  222. } else if tone == .professional {
  223. results = results.map { variant in
  224. (title: "[Analysis] " + variant.title, score: variant.score - 2, reasoning: variant.reasoning + " (professional tone)")
  225. }
  226. }
  227. return results.sorted { $0.score > $1.score }
  228. }
  229. }