summaryrefslogtreecommitdiff
path: root/Hutch/Views/Repositories/RepositoryListViewModel.swift
blob: 1e830bb03ba4caec1bd227bd3062a3e11b9e7d37 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
import Foundation

enum RepositoryCreationService: String, CaseIterable, Identifiable, Sendable {
    case git
    case hg

    var id: String { rawValue }

    var service: SRHTService {
        switch self {
        case .git: .git
        case .hg: .hg
        }
    }

    var displayName: String {
        switch self {
        case .git: "Git"
        case .hg: "Mercurial"
        }
    }
}

/// View model for the repository list screen.
@Observable
@MainActor
final class RepositoryListViewModel {
    private static let searchHistoryScopeID = "repositories"

    private(set) var repositories: [RepositorySummary] = []
    private(set) var latestBuildStatuses: [String: RepositoryBuildStatus] = [:]
    private(set) var recentSearches: [ScopedSearchHistoryEntry]
    private(set) var isLoading = false
    private(set) var isLoadingMore = false
    private(set) var isRefreshing = false
    var error: String?

    var searchText = ""

    private(set) var cursor: String?
    private(set) var hasMore = false
    private(set) var isSearching = false
    private(set) var isCreatingRepository = false
    private(set) var hasLoadedSearchIndex = false
    private var searchIndex: [RepositorySummary] = []
    private let client: SRHTClient
    private let defaults: UserDefaults
    private var buildStatusTask: Task<Void, Never>?
    private var lastBuildStatusRefresh: Date?

    private static let gitCacheKey = "git.repositories"
    private static let hgCacheKey = "hg.repositories"
    private static let buildsCacheKey = "builds.repository-status"
    private static let minimumRemoteSearchLength = 3

    init(client: SRHTClient, defaults: UserDefaults = .standard) {
        self.client = client
        self.defaults = defaults
        self.recentSearches = ScopedSearchHistoryStore.load(
            scopeID: Self.searchHistoryScopeID,
            defaults: defaults
        )
    }

    // MARK: - Queries

    private static let gitQuery = """
    query repositories($cursor: Cursor, $filter: Filter) {
        repositories(cursor: $cursor, filter: $filter) {
            results {
                id
                rid
                name
                description
                visibility
                updated
                owner { canonicalName }
                HEAD { name }
            }
            cursor
        }
    }
    """

    private static let hgQuery = """
    query repositories($cursor: Cursor) {
        repositories(cursor: $cursor) {
            results {
                id
                rid
                name
                description
                visibility
                updated
                owner { canonicalName }
                tip { branch }
            }
            cursor
        }
    }
    """

    private static let createRepositoryMutation = """
    mutation createRepository($name: String!, $visibility: Visibility!, $description: String, $cloneUrl: String) {
        createRepository(name: $name, visibility: $visibility, description: $description, cloneUrl: $cloneUrl) {
            id
            rid
            name
            description
            visibility
            updated
            owner { canonicalName }
        }
    }
    """

    private static let createHgRepositoryMutation = """
    mutation createRepository($name: String!, $visibility: Visibility!, $description: String) {
        createRepository(name: $name, visibility: $visibility, description: $description) {
            id
            rid
            name
            description
            visibility
            updated
            owner { canonicalName }
            tip { branch }
        }
    }
    """

    private static let buildsQuery = """
    query jobs($cursor: Cursor) {
        jobs(cursor: $cursor) {
            results {
                id
                created
                status
                manifest
            }
            cursor
        }
    }
    """

    // MARK: - Public API

    /// Fetch the first page of repositories. Shows cached data instantly if available,
    /// then refreshes from the network in the background.
    /// - Parameter search: Optional search string. Pass `nil` to use the current `searchText`.
    /// - Parameter forceRefresh: When true, bypass the build-status TTL (e.g. pull-to-refresh).
    func loadRepositories(search: String? = nil, forceRefresh: Bool = false) async {
        let query = (search ?? searchText).trimmingCharacters(in: .whitespacesAndNewlines)
        let isSearch = !query.isEmpty

        // Only use cache for non-search, initial loads
        if !isSearch, repositories.isEmpty {
            loadFromCache()
        }

        // During search, never show the full-screen loading overlay (which
        // would remove the List and dismiss the keyboard). Use "refreshing"
        // instead so the list stays in the hierarchy.
        if isSearch {
            isRefreshing = true
            isSearching = true
        } else if repositories.isEmpty {
            isLoading = true
            isSearching = false
        } else {
            isRefreshing = true
            isSearching = false
        }
        error = nil
        cursor = nil
        hasMore = false

        do {
            var filteredResults: [RepositorySummary]

            if isSearch {
                if hasLoadedSearchIndex || repositories.isEmpty == false {
                    filteredResults = Self.filterRepositories(repositoriesForSearchIndex, matching: query)
                } else if Self.shouldRefreshSearchIndex(for: query) {
                    let repositories = try await fetchAllRepositories(useCache: true)
                    updateSearchIndex(with: repositories)
                    filteredResults = Self.filterRepositories(repositoriesForSearchIndex, matching: query)
                } else {
                    filteredResults = []
                }
            } else {
                let repositories = try await fetchAllRepositories(useCache: true)
                updateSearchIndex(with: repositories)
                filteredResults = repositories
            }

            repositories = filteredResults.sorted(by: repositorySortOrder)
            scheduleBuildStatusRefresh(force: forceRefresh)
        } catch {
            // Only show error if we have no cached data to fall back on
            if repositories.isEmpty {
                self.error = error.userFacingMessage
            }
        }

        isLoading = false
        isRefreshing = false
    }

    /// Load the next page if available. Called when the user scrolls near the end.
    /// Note: Pagination is disabled during search (client-side filtering).
    func loadMoreIfNeeded(currentItem: RepositorySummary) async {
        _ = currentItem
    }

    /// Remove a repository from the local list (e.g. after deletion).
    func removeRepository(id: Int) {
        repositories.removeAll { $0.id == id }
    }

    func updateRepository(_ repository: RepositorySummary) {
        if let index = repositories.firstIndex(where: { $0.id == repository.id }) {
            repositories[index] = repository
            repositories.sort(by: repositorySortOrder)
        }

        let updatedRepositories = repositoriesForSearchIndex
            .filter { $0.id != repository.id } + [repository]
        updateSearchIndex(with: updatedRepositories)
    }

    func createRepository(
        service: RepositoryCreationService,
        name: String,
        description: String,
        visibility: Visibility,
        cloneURL: String
    ) async -> RepositorySummary? {
        guard !isCreatingRepository else { return nil }

        let trimmedName = name.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !trimmedName.isEmpty else {
            error = "Enter a repository name."
            return nil
        }

        isCreatingRepository = true
        error = nil
        defer { isCreatingRepository = false }

        var variables: [String: any Sendable] = [
            "name": trimmedName,
            "visibility": visibility.rawValue
        ]
        let trimmedDescription = description.trimmingCharacters(in: .whitespacesAndNewlines)
        if !trimmedDescription.isEmpty {
            variables["description"] = trimmedDescription
        }
        let trimmedCloneURL = cloneURL.trimmingCharacters(in: .whitespacesAndNewlines)
        if !trimmedCloneURL.isEmpty {
            variables["cloneUrl"] = trimmedCloneURL
        }

        do {
            let repository: RepositorySummary
            switch service {
            case .git:
                let result = try await client.execute(
                    service: .git,
                    query: Self.createRepositoryMutation,
                    variables: variables,
                    responseType: CreateRepositoryResponse.self
                )
                repository = result.createRepository
            case .hg:
                variables.removeValue(forKey: "cloneUrl")
                let result = try await client.execute(
                    service: .hg,
                    query: Self.createHgRepositoryMutation,
                    variables: variables,
                    responseType: CreateHGRepositoryResponse.self
                )
                repository = result.createRepository.repositorySummary(service: .hg)
            }
            repositories.insert(repository, at: 0)
            insertIntoSearchIndex(repository)
            scheduleBuildStatusRefresh()
            return repository
        } catch {
            self.error = repositoryCreationErrorMessage(for: error)
            return nil
        }
    }

    private func repositoryCreationErrorMessage(for error: Error) -> String {
        "Couldn’t create the repository. \(error.userFacingMessage)"
    }

    /// Fetch ALL repositories by paginating through all available pages.
    /// Used for search functionality to ensure we search through the complete dataset.
    private func fetchAllRepositories(useCache: Bool = false) async throws -> [RepositorySummary] {
        async let gitRepositories = fetchRepositories(for: .git, useCache: useCache)
        async let hgRepositories = fetchRepositories(for: .hg, useCache: useCache)
        return try await gitRepositories + hgRepositories
    }

    /// Reset search state and reload all repositories
    func resetSearch() {
        repositories = []
        cursor = nil
        hasMore = false
        isSearching = false
    }

    func recordRecentSearch(_ query: String) {
        ScopedSearchHistoryStore.record(
            query: query,
            scopeID: Self.searchHistoryScopeID,
            defaults: defaults
        )
        recentSearches = ScopedSearchHistoryStore.load(
            scopeID: Self.searchHistoryScopeID,
            defaults: defaults
        )
    }

    func clearRecentSearches() {
        ScopedSearchHistoryStore.clear(
            scopeID: Self.searchHistoryScopeID,
            defaults: defaults
        )
        recentSearches = []
    }

    // MARK: - Private

    /// Page shape matching the GraphQL response without generic constraints that
    /// conflict with strict concurrency when used from a @MainActor context.
    private struct Page: Decodable, Sendable {
        let results: [RepositoryPayload]
        let cursor: String?
    }

    private struct RepositoriesResponse: Decodable, Sendable {
        let repositories: Page?
    }

    private struct CreateRepositoryResponse: Decodable, Sendable {
        let createRepository: RepositorySummary
    }

    private struct CreateHGRepositoryResponse: Decodable, Sendable {
        let createRepository: HGRepositoryPayload
    }

    private struct BuildJobsResponse: Decodable, Sendable {
        let jobs: BuildJobsPage
    }

    private struct BuildJobsPage: Decodable, Sendable {
        let results: [BuildStatusPayload]
        let cursor: String?
    }

    private struct BuildStatusPayload: Decodable, Sendable {
        let id: Int
        let created: Date
        let status: JobStatus
        let manifest: String?
    }

    private struct HGPage: Decodable, Sendable {
        let results: [HGRepositoryPayload]
        let cursor: String?
    }

    private struct HGRepositoriesResponse: Decodable, Sendable {
        let repositories: HGPage?
    }

    private static let emptyPage = Page(results: [], cursor: nil)

    private struct RepositoryPayload: Decodable, Sendable {
        let id: Int
        let rid: String
        let name: String
        let description: String?
        let visibility: Visibility
        let updated: Date
        let owner: Entity
        let head: Reference?

        enum CodingKeys: String, CodingKey {
            case id, rid, name, description, visibility, updated, owner
            case head = "HEAD"
        }

        func repositorySummary(service: SRHTService) -> RepositorySummary {
            RepositorySummary(
                id: id,
                rid: rid,
                service: service,
                name: name,
                description: description,
                visibility: visibility,
                updated: updated,
                owner: owner,
                head: head
            )
        }
    }

    private struct HGRepositoryPayload: Decodable, Sendable {
        let id: Int
        let rid: String
        let name: String
        let description: String?
        let visibility: Visibility
        let updated: Date
        let owner: Entity
        let tip: HGTipReference?

        func repositorySummary(service: SRHTService) -> RepositorySummary {
            RepositorySummary(
                id: id,
                rid: rid,
                service: service,
                name: name,
                description: description,
                visibility: visibility,
                updated: updated,
                owner: owner,
                head: tip.map { Reference(name: $0.branch, target: nil) }
            )
        }
    }

    private struct HGTipReference: Decodable, Sendable {
        let branch: String
    }

    private var repositoriesForSearchIndex: [RepositorySummary] {
        searchIndex
    }

    func latestBuildStatus(for repository: RepositorySummary) -> RepositoryBuildStatus {
        latestBuildStatuses[Self.buildStatusCacheKey(for: repository)] ?? RepositoryBuildStatus.none
    }

    private func fetchPage(
        service: SRHTService,
        cursor: String?,
        search: String? = nil,
        useCache: Bool
    ) async throws -> Page {
        var variables: [String: any Sendable] = [:]
        if let cursor {
            variables["cursor"] = cursor
        }
        let trimmed = (search ?? searchText).trimmingCharacters(in: .whitespacesAndNewlines)
        if !trimmed.isEmpty {
            variables["filter"] = ["search": trimmed] as [String: any Sendable]
        }

        if useCache && cursor == nil {
            switch service {
            case .git:
                let result = try await client.executeAndCache(
                    service: service,
                    query: Self.gitQuery,
                    variables: variables.isEmpty ? nil : variables,
                    responseType: RepositoriesResponse.self,
                    cacheKey: cacheKey(for: service)
                )
                return result.repositories ?? Self.emptyPage
            case .hg:
                let hgVariables = cursor.map { ["cursor": $0 as any Sendable] }
                let result = try await client.executeAndCache(
                    service: service,
                    query: Self.hgQuery,
                    variables: hgVariables,
                    responseType: HGRepositoriesResponse.self,
                    cacheKey: cacheKey(for: service)
                )
                return Page(
                    results: result.repositories?.results.map {
                        RepositoryPayload(
                            id: $0.id,
                            rid: $0.rid,
                            name: $0.name,
                            description: $0.description,
                            visibility: $0.visibility,
                            updated: $0.updated,
                            owner: $0.owner,
                            head: $0.tip.map { Reference(name: $0.branch, target: nil) }
                        )
                    } ?? [],
                    cursor: result.repositories?.cursor
                )
            default:
                let result = try await client.executeAndCache(
                    service: service,
                    query: Self.gitQuery,
                    variables: variables.isEmpty ? nil : variables,
                    responseType: RepositoriesResponse.self,
                    cacheKey: cacheKey(for: service)
                )
                return result.repositories ?? Self.emptyPage
            }
        } else {
            switch service {
            case .git:
                let result = try await client.execute(
                    service: service,
                    query: Self.gitQuery,
                    variables: variables.isEmpty ? nil : variables,
                    responseType: RepositoriesResponse.self
                )
                return result.repositories ?? Self.emptyPage
            case .hg:
                let hgVariables = cursor.map { ["cursor": $0 as any Sendable] }
                let result = try await client.execute(
                    service: service,
                    query: Self.hgQuery,
                    variables: hgVariables,
                    responseType: HGRepositoriesResponse.self
                )
                return Page(
                    results: result.repositories?.results.map {
                        RepositoryPayload(
                            id: $0.id,
                            rid: $0.rid,
                            name: $0.name,
                            description: $0.description,
                            visibility: $0.visibility,
                            updated: $0.updated,
                            owner: $0.owner,
                            head: $0.tip.map { Reference(name: $0.branch, target: nil) }
                        )
                    } ?? [],
                    cursor: result.repositories?.cursor
                )
            default:
                let result = try await client.execute(
                    service: service,
                    query: Self.gitQuery,
                    variables: variables.isEmpty ? nil : variables,
                    responseType: RepositoriesResponse.self
                )
                return result.repositories ?? Self.emptyPage
            }
        }
    }

    private func loadFromCache() {
        let cachedRepositories = [SRHTService.git, .hg].flatMap { service -> [RepositorySummary] in
            guard let data = client.responseCache.get(forKey: cacheKey(for: service)) else { return [] }
            let decoder = JSONDecoder()
            decoder.dateDecodingStrategy = .srhtFlexible
            switch service {
            case .git:
                if let response = try? decoder.decode(
                    GraphQLResponse<RepositoriesResponse>.self,
                    from: data
                ), let repos = response.data?.repositories {
                    return repos.results.map { $0.repositorySummary(service: service) }
                }
            case .hg:
                if let response = try? decoder.decode(
                    GraphQLResponse<HGRepositoriesResponse>.self,
                    from: data
                ), let repos = response.data?.repositories {
                    return repos.results.map { $0.repositorySummary(service: service) }
                }
            default:
                break
            }
            return []
        }
        if !cachedRepositories.isEmpty {
            let sortedRepositories = cachedRepositories.sorted(by: repositorySortOrder)
            repositories = sortedRepositories
            updateSearchIndex(with: sortedRepositories)
            scheduleBuildStatusRefresh()
        }
    }

    private func scheduleBuildStatusRefresh(force: Bool = false) {
        // Skip if we already refreshed recently (120-second TTL). Pull-to-refresh
        // passes force: true to bypass this check.
        if !force, let last = lastBuildStatusRefresh,
           Date().timeIntervalSince(last) < 120 {
            return
        }
        let repositoriesSnapshot = repositories
        buildStatusTask?.cancel()
        buildStatusTask = Task { [weak self] in
            guard let self else { return }
            await self.loadLatestBuildStatuses(for: repositoriesSnapshot)
        }
    }

    private func loadLatestBuildStatuses(for repositories: [RepositorySummary]) async {
        let targetKeys = Set(repositories.map(Self.buildStatusCacheKey(for:)))
        guard !targetKeys.isEmpty else {
            await MainActor.run {
                latestBuildStatuses = [:]
            }
            return
        }

        var resolvedStatuses: [String: (Date, RepositoryBuildStatus)] = [:]
        var cursor: String?
        var shouldUseCache = true

        do {
            while !Task.isCancelled {
                let page = try await fetchBuildStatusPage(cursor: cursor, useCache: shouldUseCache)
                shouldUseCache = false

                for job in page.results {
                    let jobStatus = Self.repositoryBuildStatus(for: job.status)
                    guard let manifest = job.manifest else { continue }

                    for key in Self.buildStatusKeys(in: manifest) where targetKeys.contains(key) {
                        let existing = resolvedStatuses[key]
                        if existing == nil || existing!.0 < job.created {
                            resolvedStatuses[key] = (job.created, jobStatus)
                        }
                    }
                }

                if resolvedStatuses.count == targetKeys.count || page.cursor == nil {
                    break
                }
                cursor = page.cursor
            }

            let finalStatuses = targetKeys.reduce(into: [String: RepositoryBuildStatus]()) { result, key in
                result[key] = resolvedStatuses[key]?.1 ?? RepositoryBuildStatus.none
            }

            await MainActor.run {
                guard repositories == self.repositories else { return }
                latestBuildStatuses = finalStatuses
                lastBuildStatusRefresh = Date()
            }
        } catch {
            // Build status is auxiliary data for the list. Leave the default gray state on failure.
        }
    }

    private func fetchBuildStatusPage(cursor: String?, useCache: Bool) async throws -> BuildJobsPage {
        var variables: [String: any Sendable] = [:]
        if let cursor {
            variables["cursor"] = cursor
        }

        if useCache && cursor == nil {
            let result = try await client.executeAndCache(
                service: .builds,
                query: Self.buildsQuery,
                variables: variables.isEmpty ? nil : variables,
                responseType: BuildJobsResponse.self,
                cacheKey: Self.buildsCacheKey
            )
            return result.jobs
        }

        let result = try await client.execute(
            service: .builds,
            query: Self.buildsQuery,
            variables: variables.isEmpty ? nil : variables,
            responseType: BuildJobsResponse.self
        )
        return result.jobs
    }

    private func fetchRepositories(for service: SRHTService, useCache: Bool) async throws -> [RepositorySummary] {
        var allRepositories: [RepositorySummary] = []
        var currentCursor: String? = nil

        while true {
            let page = try await fetchPage(
                service: service,
                cursor: currentCursor,
                search: nil,
                useCache: useCache && currentCursor == nil
            )
            allRepositories.append(contentsOf: page.results.map { $0.repositorySummary(service: service) })
            guard let nextCursor = page.cursor else { break }
            currentCursor = nextCursor
        }

        return allRepositories
    }

    private func cacheKey(for service: SRHTService) -> String {
        switch service {
        case .git:
            Self.gitCacheKey
        case .hg:
            Self.hgCacheKey
        default:
            "\(service.rawValue).repositories"
        }
    }

    private func repositorySortOrder(lhs: RepositorySummary, rhs: RepositorySummary) -> Bool {
        if lhs.updated == rhs.updated {
            if lhs.service == rhs.service {
                return lhs.name.localizedCaseInsensitiveCompare(rhs.name) == .orderedAscending
            }
            return lhs.service.rawValue < rhs.service.rawValue
        }
        return lhs.updated > rhs.updated
    }

    private func updateSearchIndex(with repositories: [RepositorySummary]) {
        searchIndex = repositories.sorted(by: repositorySortOrder)
        hasLoadedSearchIndex = !searchIndex.isEmpty
    }

    private func insertIntoSearchIndex(_ repository: RepositorySummary) {
        let updatedRepositories = (repositoriesForSearchIndex + [repository])
            .uniqued(on: \.id)
            .sorted(by: repositorySortOrder)
        updateSearchIndex(with: updatedRepositories)
    }

    static func shouldRefreshSearchIndex(for query: String) -> Bool {
        query.trimmingCharacters(in: .whitespacesAndNewlines).count >= Self.minimumRemoteSearchLength
    }

    static func filterRepositories(_ repositories: [RepositorySummary], matching query: String) -> [RepositorySummary] {
        let lowercasedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        guard !lowercasedQuery.isEmpty else { return repositories }

        return repositories.filter { repo in
            repo.name.lowercased().contains(lowercasedQuery) ||
            repo.owner.canonicalName.lowercased().contains(lowercasedQuery) ||
            repo.defaultBranchName?.lowercased().contains(lowercasedQuery) ?? false ||
            repo.description?.lowercased().contains(lowercasedQuery) ?? false
        }
    }

    nonisolated static func buildStatusCacheKey(for repository: RepositorySummary) -> String {
        buildStatusCacheKey(
            service: repository.service,
            ownerCanonicalName: repository.owner.canonicalName,
            repositoryName: repository.name
        )
    }

    nonisolated static func buildStatusCacheKey(
        service: SRHTService,
        ownerCanonicalName: String,
        repositoryName: String
    ) -> String {
        "\(service.rawValue)|\(ownerCanonicalName.lowercased())|\(repositoryName.lowercased())"
    }

    nonisolated static func repositoryBuildStatus(for jobStatus: JobStatus) -> RepositoryBuildStatus {
        switch jobStatus {
        case .success:
            .success
        case .pending, .queued, .running:
            .running
        case .failed, .cancelled, .timeout:
            .failed
        }
    }

    nonisolated static func buildStatusKeys(in manifest: String) -> Set<String> {
        let pattern = #"(?:https://|ssh://(?:git|hg)@|(?:git|hg)@)(git|hg)\.sr\.ht[:/]([~][^/\s]+)/([^\s"'#]+)"#
        guard let regex = try? NSRegularExpression(pattern: pattern, options: [.caseInsensitive]) else {
            return []
        }

        let nsRange = NSRange(manifest.startIndex..<manifest.endIndex, in: manifest)
        return regex.matches(in: manifest, options: [], range: nsRange).reduce(into: Set<String>()) { result, match in
            guard
                let serviceRange = Range(match.range(at: 1), in: manifest),
                let ownerRange = Range(match.range(at: 2), in: manifest),
                let nameRange = Range(match.range(at: 3), in: manifest)
            else {
                return
            }

            let service: SRHTService = manifest[serviceRange].lowercased() == "hg" ? .hg : .git
            let owner = String(manifest[ownerRange]).lowercased()
            var name = String(manifest[nameRange]).lowercased()

            if let suffixRange = name.range(of: ".git", options: [.backwards, .anchored]) {
                name.removeSubrange(suffixRange)
            }
            name = name.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
            if !name.isEmpty {
                result.insert(buildStatusCacheKey(
                    service: service,
                    ownerCanonicalName: owner,
                    repositoryName: name
                ))
            }
        }
    }
}

private extension Array {
    func uniqued<ID: Hashable>(on keyPath: KeyPath<Element, ID>) -> [Element] {
        var seenIDs: Set<ID> = []
        return filter { element in
            seenIDs.insert(element[keyPath: keyPath]).inserted
        }
    }
}