// Everything Days asks of the core (CONTRACT.md, `days.*`), each answer read // as the contract shapes it (`DaysAnswers`). Days reads the core alone // (`CoreDaysBook`): every method is `[new]` since f2f420f65; no made-up days. import CottonKit import Foundation protocol DaysBook: Sendable { /// `group`: the filter's chosen group (contract §5b), nil for all. /// `keep`: the to-dos ticked or unticked since the list was opened, each /// to stay where it stood (contract §2 Keep). func span(from: String, to: String, group: String?, keep: [DaysKept]) async throws -> DaysSpanAnswer func sometime(group: String?, keep: [DaysKept]) async throws -> [DaysGroup] func groups() async throws -> DaysGroups func month(_ month: String, weekStart: Int, group: String?) async throws -> DaysMonth func readLine(_ words: String, where: String, dayInView: String?) async throws -> DaysReadLine func add(_ words: String, where: String, dayInView: String?, day: String??, time: String?, mark: String?, group: String?) async throws -> DaysAdded? func item(table: String, id: String, occurrenceAt: String?) async throws -> DaysItem func change(table: String, id: String, occurrenceAt: String?, _ change: DaysChange) async throws func done(_ id: String, _ done: Bool) async throws func move(table: String, id: String, day: String?, occurrenceAt: String?) async throws func marks() async throws -> [DaysCatalogueMark] func findMarks(_ words: String) async throws -> [String] /// `days.show` (contract §11): late, repeating, dropped or done, a page from `after`. func show(_ view: String, after: String?, keep: [DaysKept]) async throws -> DaysShown /// `days.find` (contract §12): everything Days keeps that the words find. func find(_ words: String, keep: [DaysKept]) async throws -> DaysFound /// `days.drop`, `days.bring_back` (contract §3): decided not to do it, and back again. func drop(_ id: String, back: Bool) async throws /// `days.delete` (contract §3): into the bin; one occurrence of a repeating event of the person's own. func delete(table: String, id: String, occurrenceAt: String?) async throws /// `days.people_find` (contract §15): the person's contacts with an email and their people on Cotton. func peopleFind(_ words: String, eventId: String?) async throws -> [DaysPerson] /// `days.tell` (contract §15): what saving this list of people would tell whom, before Save. func tell(eventId: String, people: [DaysPerson]) async throws -> DaysTold /// `days.change`, with what it said back (contract §15, §16): `google_needs_write` is thrown as the core's refusal. func changed(table: String, id: String, occurrenceAt: String?, _ change: DaysChange) async throws -> DaysChanged /// `days.send_to_google`, then `days.invitations` (contract §16, §17): what waits goes, what came in lands. func send() async throws -> DaysSent /// `days.answer` (contract §17): an invitation received, answered. func answer(_ id: String, _ answer: String) async throws } extension DaysBook { func span(from: String, to: String) async throws -> DaysSpanAnswer { try await span(from: from, to: to, group: nil, keep: []) } func span(from: String, to: String, group: String?) async throws -> DaysSpanAnswer { try await span(from: from, to: to, group: group, keep: []) } func sometime(group: String?) async throws -> [DaysGroup] { try await sometime(group: group, keep: []) } func add(_ words: String, where: String, dayInView: String?, day: String??, time: String?, mark: String?) async throws -> DaysAdded? { try await add(words, where: `where`, dayInView: dayInView, day: day, time: time, mark: mark, group: nil) } } /// A refusal the book itself says, as the core's `MethodError` would. struct DaysRefused: LocalizedError, Sendable { let code: String let message: String var errorDescription: String? { message } } /// The phone's own today and zone: every read's common arguments (contract §0). struct DaysClock: Sendable { var zone: @Sendable () -> TimeZone = { .current } var now: @Sendable () -> Date = { Date() } var calendar: DaysCalendar { DaysCalendar(zone: zone()) } var today: String { calendar.key(now()) } static let phone = DaysClock() /// A clock standing on one day, for tests and looks. static func fixed(_ day: String, zone: TimeZone = TimeZone(identifier: "UTC")!) -> DaysClock { let date = DaysCalendar(zone: zone).date(day) return DaysClock(zone: { zone }, now: { date }) } } /// Days as `YYYY-MM-DD` keys in one zone: the only date arithmetic the phone /// does, which is choosing which span to ask for and saying a key short. struct DaysCalendar: Sendable { let zone: TimeZone var gregorian: Calendar { var c = Calendar(identifier: .gregorian) c.timeZone = zone c.locale = Locale(identifier: "en_GB") return c } /// Noon on [key], in the zone (noon, so no daylight change moves the day). func date(_ key: String) -> Date { let parts = key.split(separator: "-").compactMap { Int($0) } guard parts.count == 3 else { return Date() } return gregorian.date(from: DateComponents(year: parts[0], month: parts[1], day: parts[2], hour: 12)) ?? Date() } func key(_ date: Date) -> String { let c = gregorian.dateComponents([.year, .month, .day], from: date) return String(format: "%04d-%02d-%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0) } func adding(_ days: Int, to key: String) -> String { self.key(gregorian.date(byAdding: .day, value: days, to: date(key)) ?? date(key)) } func between(_ a: String, _ b: String) -> Int { gregorian.dateComponents([.day], from: date(a), to: date(b)).day ?? 0 } /// ISO weekday: Monday 1 … Sunday 7. func isoWeekday(_ key: String) -> Int { let w = gregorian.component(.weekday, from: date(key)) // Sunday 1 return w == 1 ? 7 : w - 1 } func dayOfMonth(_ key: String) -> Int { gregorian.component(.day, from: date(key)) } func month(_ key: String) -> Int { gregorian.component(.month, from: date(key)) } func year(_ key: String) -> Int { gregorian.component(.year, from: date(key)) } func format(_ key: String, _ pattern: String, locale: Locale = Locale(identifier: "en_GB")) -> String { let f = DateFormatter() f.calendar = gregorian f.timeZone = zone f.locale = locale f.dateFormat = pattern return f.string(from: date(key)) } /// A day as the pill says it (Thu 26 Nov), in the phone's own words for weekdays and months. func short(_ key: String) -> String { format(key, "EEE d MMM", locale: .current) } } // MARK: - The core /// The core's `days.*` (cotton-ffi `cotton_call`). struct CoreDaysBook: DaysBook { let core: any CottonCalling var clock: DaysClock = .phone /// An answer that asks leave to notify (`platform_action: request_notifications`, with `leave`'s words): an add, /// a change or a move just gave an item its first reminder on a phone never asked (DECISIONS "Alerts"). var onLeave: (@Sendable (DaysLeave) -> Void)? = nil fileprivate func ask(_ method: String, _ fields: [String: Any] = [:]) async throws -> Any { var body = fields body["timezone"] = clock.zone().identifier body["today"] = clock.today let answer = try await core.callJSON(method, JSONValue.days(body)) if answer["platform_action"]?.string == "request_notifications", let onLeave { let leave = answer["leave"] onLeave(DaysLeave(title: leave?["title"]?.string, body: leave?["body"]?.string ?? "", go: leave?["go"]?.string ?? "", notNow: leave?["notNow"]?.string)) } return answer.daysAny } fileprivate func object(_ method: String, _ fields: [String: Any] = [:]) async throws -> DaysRead.Object { (try await ask(method, fields) as? DaysRead.Object) ?? [:] } /// The most days one `days.span` answers (CONTRACT §2: a year and a /// little, so a long quiet run is one fold; as Android's bd81b91d54). static let mostDays = 370 /// `days.span`, asked in reads of at most 370 days and joined, never /// two folds in a row (DECISIONS, 21 Nov 2026). A fold at an edge of a /// read may reach past it (contract §2, Edge folds reach): the next read /// starts past it. Where a quiet stretch still runs over the edge of two /// reads (a fold ending one and a fold starting the next), the core is /// asked for the two as one read, so its one fold says the stretch in its /// own words; a stretch longer than one read is joined here, in the /// days line set's words. A read that says the list ends (`end`) is the /// last; one that says where it begins (`begins`) is kept. func span(from: String, to: String, group: String?, keep: [DaysKept]) async throws -> DaysSpanAnswer { let cal = clock.calendar var only: [String: Any] = [:] if let group { only["group"] = group } if !keep.isEmpty { only["keep"] = keep.map(\.json) } var out = DaysSpanAnswer(today: clock.today, days: []) var start = from var first = true while start <= to { let end = min(cal.adding(Self.mostDays - 1, to: start), to) let part = DaysRead.span(try await object("days.span", only.merging(["from": start, "to": end]) { $1 })) out.today = part.today if first { out.begins = part.begins } first = false var next = part.days if case .fold(let before)? = out.days.last, case .fold(let after)? = next.first { out.days.removeLast() next.removeFirst() if cal.between(before.from, after.to) < Self.mostDays { let joined = DaysRead.span(try await object("days.span", only.merging(["from": before.from, "to": after.to]) { $1 })) out.days += joined.days } else { out.days.append(.fold(Self.joined(before, after, cal))) } } out.days += next if let said = part.end { out.end = said break } start = cal.adding(1, to: end) // A fold reaching past this read's end: the next read starts past it. if case .fold(let last)? = out.days.last, last.to >= start { start = cal.adding(1, to: last.to) } } out.days = Self.oneFoldAtATime(out.days, cal) return out } /// Never two folds in a row: two that meet are one, from the first's /// first day to the second's last. static func oneFoldAtATime(_ days: [DaysSpan], _ cal: DaysCalendar) -> [DaysSpan] { var out: [DaysSpan] = [] for entry in days { if case .fold(let after) = entry, case .fold(let before)? = out.last { out[out.count - 1] = .fold(joined(before, after, cal)) } else { out.append(entry) } } return out } /// Two folds as one, said as the core says a fold ("22 – 25 · four quiet /// days"; across months, "30 Nov – 2 Dec · …") in the days line set. static func joined(_ a: DaysFold, _ b: DaysFold, _ cal: DaysCalendar) -> DaysFold { let from = min(a.from, b.from), to = max(a.to, b.to) let count = cal.between(from, to) + 1 let sameMonth = from.prefix(7) == to.prefix(7) let saidFrom = sameMonth ? String(cal.dayOfMonth(from)) : cal.format(from, "d MMM") let saidTo = sameMonth ? String(cal.dayOfMonth(to)) : cal.format(to, "d MMM") let n = (2...10).contains(count) ? ShellLines.line("days", "count.\(count)") : String(count) return DaysFold(from: from, to: to, count: count, words: ShellLines.line("days", "fold.other", ["from": saidFrom, "to": saidTo, "n": n])) } func sometime(group: String?, keep: [DaysKept]) async throws -> [DaysGroup] { var f: [String: Any] = [:] if let group { f["group"] = group } if !keep.isEmpty { f["keep"] = keep.map(\.json) } return DaysRead.groups(try await ask("days.sometime", f)) } func groups() async throws -> DaysGroups { DaysRead.groupCounts(try await object("days.groups")) } func month(_ month: String, weekStart: Int, group: String?) async throws -> DaysMonth { var f: [String: Any] = ["month": month, "weekStart": weekStart] if let group { f["group"] = group } return DaysRead.month(try await object("days.month", f)) } func readLine(_ words: String, where: String, dayInView: String?) async throws -> DaysReadLine { var f: [String: Any] = ["words": words, "where": `where`] if let dayInView { f["dayInView"] = dayInView } return DaysRead.readLine(try await object("days.read_line", f)) } /// `days.add` answers where the new item landed (`{table, id, day, time}`). func add(_ words: String, where: String, dayInView: String?, day: String??, time: String?, mark: String?, group: String?) async throws -> DaysAdded? { var f: [String: Any] = ["words": words, "where": `where`] if let group { f["group"] = group } if let dayInView { f["dayInView"] = dayInView } if let day { f["day"] = day.map { $0 as Any } ?? NSNull() } if let time { f["time"] = time } if let mark { f["mark"] = mark } return DaysRead.added(try await object("days.add", f)) } /// The sheet: `days.item` (a to-do's group as `{ id, name }`), and for a /// to-do the groups to choose from, same-named groups as one (`days.groups`). func item(table: String, id: String, occurrenceAt: String?) async throws -> DaysItem { var f: [String: Any] = ["table": table, "id": id] if let occurrenceAt { f["occurrenceAt"] = occurrenceAt } var item = DaysRead.item(table: table, id: id, try await object("days.item", f)) if table == "todo" { item.groups = try await groups().groups.map { DaysGroupChoice(id: $0.id, name: $0.name) } } return item } /// `days.change` with what changed; a to-do's group goes in it too /// (`group: id` files it there alone, `null` takes it out of every group). func change(table: String, id: String, occurrenceAt: String?, _ change: DaysChange) async throws { _ = try await changed(table: table, id: id, occurrenceAt: occurrenceAt, change) } func changed(table: String, id: String, occurrenceAt: String?, _ change: DaysChange) async throws -> DaysChanged { var f = change.json if table == "todo", let group = change.group { f["group"] = group.map { $0 as Any } ?? NSNull() } guard !f.isEmpty else { return DaysChanged() } f["table"] = table f["id"] = id if let occurrenceAt { f["occurrenceAt"] = occurrenceAt } return DaysRead.changed(try await object("days.change", f)) } func done(_ id: String, _ done: Bool) async throws { _ = try await ask(done ? "days.done" : "days.undone", ["id": id]) } func move(table: String, id: String, day: String?, occurrenceAt: String?) async throws { var f: [String: Any] = ["table": table, "id": id, "day": day.map { $0 as Any } ?? NSNull()] if let occurrenceAt { f["occurrenceAt"] = occurrenceAt } _ = try await ask("days.move", f) } /// `days.marks`: the marks that have a drawing, with their strokes. func marks() async throws -> [DaysCatalogueMark] { DaysRead.catalogue(try await core.callJSON("days.marks", JSONValue.object([:])).daysAny) } func findMarks(_ words: String) async throws -> [String] { let answer = try await core.callJSON("days.marks.find", JSONValue.days(["words": words])).daysAny return DaysRead.strings((answer as? DaysRead.Object) ?? [:], "marks") } } extension CoreDaysBook { func show(_ view: String, after: String?, keep: [DaysKept]) async throws -> DaysShown { var f: [String: Any] = ["view": view] if let after { f["after"] = after } if !keep.isEmpty { f["keep"] = keep.map(\.json) } return DaysRead.shown(try await object("days.show", f)) } func find(_ words: String, keep: [DaysKept]) async throws -> DaysFound { var f: [String: Any] = ["words": words] if !keep.isEmpty { f["keep"] = keep.map(\.json) } return DaysRead.found(try await object("days.find", f)) } func drop(_ id: String, back: Bool) async throws { _ = try await ask(back ? "days.bring_back" : "days.drop", ["id": id]) } func delete(table: String, id: String, occurrenceAt: String?) async throws { var f: [String: Any] = ["table": table, "id": id] if let occurrenceAt { f["occurrenceAt"] = occurrenceAt } _ = try await ask("days.delete", f) } } extension JSONValue { /// A Foundation value as JSON (`NSNull` is null). static func days(_ any: Any) -> JSONValue { switch any { case is NSNull: return .null case let b as Bool: return .bool(b) case let n as Int: return .number(Double(n)) case let n as Double: return .number(n) case let s as String: return .string(s) case let a as [Any]: return .array(a.map(days)) case let o as [String: Any]: return .object(o.mapValues(days)) default: return .null } } /// The JSON as Foundation values, as `DaysRead` reads them. var daysAny: Any { switch self { case .null: return NSNull() case .bool(let b): return b case .number(let n): return NSNumber(value: n) case .string(let s): return s case .array(let a): return a.map(\.daysAny) case .object(let o): return o.mapValues(\.daysAny) } } } extension CoreDaysBook { func peopleFind(_ words: String, eventId: String?) async throws -> [DaysPerson] { var f: [String: Any] = ["words": words] if let eventId { f["eventId"] = eventId } return DaysRead.objects(try await object("days.people_find", f), "rows").compactMap(DaysRead.person) } func tell(eventId: String, people: [DaysPerson]) async throws -> DaysTold { let x = try await object("days.tell", ["table": "event", "id": eventId, "people": people.map(\.json)]) return DaysTold(lines: DaysRead.strings(x, "lines"), blocked: DaysRead.o(x, "blocked").flatMap { DaysRead.s($0, "line") }) } /// Google first, then people on Cotton, as Android's DaysBook.send: their lines together, Google's ask first. func send() async throws -> DaysSent { let google = DaysRead.sent(try await object("days.send_to_google")) let cotton = DaysRead.sent(try await object("days.invitations")) var out = google out.said += cotton.said if out.reconnect == nil { out.reconnect = cotton.reconnect #if os(iOS) out.connect = cotton.connect #endif } return out } func answer(_ id: String, _ answer: String) async throws { _ = try await ask("days.answer", ["id": id, "answer": answer]) } }