// Auteur : Simon-Pierre Boucher — contact@spboucher.ai // Services.swift — réseau : client JSON avec cache disque (mode hors ligne de // consultation), service d'univers (listes/recherche), stats live, et // KA Agent (chat SSE vers l'API centrale api-ka). import Foundation // MARK: - Client HTTP + cache disque actor APIClient { static let shared = APIClient() private let session: URLSession private let cacheDir: URL init() { let cfg = URLSessionConfiguration.default cfg.timeoutIntervalForRequest = 15 cfg.waitsForConnectivity = false session = URLSession(configuration: cfg) cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] .appendingPathComponent("ka-json", isDirectory: true) try? FileManager.default.createDirectory(at: cacheDir, withIntermediateDirectories: true) } private func cacheFile(for url: URL) -> URL { let name = url.absoluteString.data(using: .utf8)!.base64EncodedString() .replacingOccurrences(of: "/", with: "_") return cacheDir.appendingPathComponent(String(name.suffix(120)) + ".json") } /// JSON brut ; en cas d'échec réseau, sert la dernière copie disque (hors ligne). func json(_ url: URL, ttl: TimeInterval = 120) async throws -> JSONValue { let file = cacheFile(for: url) if let attrs = try? FileManager.default.attributesOfItem(atPath: file.path), let date = attrs[.modificationDate] as? Date, Date().timeIntervalSince(date) < ttl, let data = try? Data(contentsOf: file), let cached = try? JSONDecoder().decode(JSONValue.self, from: data) { return cached } do { var req = URLRequest(url: url) req.setValue("KA-iOS/1.0 (+https://www.groupe-ka.com)", forHTTPHeaderField: "User-Agent") let (data, resp) = try await session.data(for: req) guard let http = resp as? HTTPURLResponse, http.statusCode == 200 else { throw URLError(.badServerResponse) } let value = try JSONDecoder().decode(JSONValue.self, from: data) try? data.write(to: file) return value } catch { if let data = try? Data(contentsOf: file), let cached = try? JSONDecoder().decode(JSONValue.self, from: data) { return cached // hors ligne : dernier contenu connu } throw error } } } // MARK: - Univers : listes, recherche, stats enum UniverseService { static func listURL(_ u: Universe, query: String?, city: String? = nil, limit: Int = 30, params: [String: String] = [:]) -> URL? { guard let path = u.listPath else { return nil } var comps = URLComponents(url: u.baseURL.appendingPathComponent(""), resolvingAgainstBaseURL: false)! // listPath peut contenir déjà une query (ex. events?upcoming=true) let split = path.split(separator: "?", maxSplits: 1) comps.path = String(split[0]) var items: [URLQueryItem] = split.count > 1 ? split[1].split(separator: "&").map { let kv = $0.split(separator: "=", maxSplits: 1) return URLQueryItem(name: String(kv[0]), value: kv.count > 1 ? String(kv[1]) : nil) } : [] if let q = query, !q.isEmpty { items.append(.init(name: u.searchParam, value: q)) } if let c = city, !c.isEmpty { items.append(.init(name: "city", value: c)) } for (k, v) in params.sorted(by: { $0.key < $1.key }) where !v.isEmpty { items.append(.init(name: k, value: v)) } items.append(.init(name: "limit", value: String(limit))) comps.queryItems = items return comps.url } static func fetch(_ u: Universe, query: String? = nil, city: String? = nil, limit: Int = 30, params: [String: String] = [:]) async throws -> [KAItem] { // Trouve·Ka : /api/search EXIGE q (422 sinon) — jamais d'appel à vide if u.id == "trouve-ka", (query ?? "").isEmpty { return [] } guard let url = listURL(u, query: query, city: city, limit: limit, params: params), let map = u.map else { return [] } let root = try await APIClient.shared.json(url) let obj = root.object ?? [:] let raw = obj[u.itemsKey]?.array ?? obj["items"]?.array ?? obj["results"]?.array ?? obj["hits"]?.array ?? root.array ?? [] return raw.compactMap { $0.object.flatMap(map) } } /// Total d'une requête (champ `total` de la réponse liste) — pour les alertes. static func total(_ u: Universe, query: String? = nil, params: [String: String] = [:]) async -> Int? { guard let url = listURL(u, query: query, limit: 1, params: params), let root = try? await APIClient.shared.json(url, ttl: 60) else { return nil } return root.object?.num("total", "count").map(Int.init) } /// Items GÉOLOCALISÉS pour une région de carte. /// lou-ka / immo-ka / job-ka : endpoint geojson avec bbox RÉEL (vérifié). /// Autres univers : liste standard filtrée client sur la région. static func mapItems(_ u: Universe, west: Double, south: Double, east: Double, north: Double, limit: Int = 150) async -> [KAItem] { let bboxCapable = ["lou-ka": "/api/listings.geojson", "immo-ka": "/api/listings.geojson", "job-ka": "/api/jobs.geojson"] if let path = bboxCapable[u.id], let map = u.map { var comps = URLComponents(string: "https://\(u.domain)\(path)")! comps.queryItems = [ .init(name: "bbox", value: "\(west),\(south),\(east),\(north)"), .init(name: "limit", value: String(limit)), ] guard let url = comps.url, let root = try? await APIClient.shared.json(url, ttl: 90), let features = root.object?["features"]?.array else { return [] } return features.compactMap { f -> KAItem? in guard let fo = f.object, var props = fo["properties"]?.object, let coords = fo["geometry"]?.object?["coordinates"]?.array, coords.count >= 2, let lon = coords[0].number, let lat = coords[1].number else { return nil } props["lat"] = .number(lat) props["lng"] = .number(lon) return map(props) } } // repli : liste + filtre client let items = (try? await fetch(u, limit: limit)) ?? [] return items.filter { it in guard let la = it.latitude, let lo = it.longitude else { return false } return la >= south && la <= north && lo >= west && lo <= east } } /// Couche VRAI-PRIX de la carte : les unités d'évaluation du Québec /// (3 747 008 au total) dans la ZONE VISIBLE seulement, via /api/nearby /// (bbox plafonné serveur ~9 km, cache APIClient). La carte ne l'appelle /// qu'assez zoomée — jamais de chargement massif. static func vraiPrixUnits(west: Double, south: Double, east: Double, north: Double, limit: Int = 1000) async -> [KAItem] { var comps = URLComponents(string: "https://www.vrai-prix.com/api/nearby")! comps.queryItems = [ .init(name: "lat", value: "\((south + north) / 2)"), .init(name: "lng", value: "\((west + east) / 2)"), .init(name: "halfLat", value: "\(min((north - south) / 2, 0.08))"), .init(name: "halfLng", value: "\(min((east - west) / 2, 0.12))"), .init(name: "limit", value: String(limit)), ] guard let url = comps.url, let root = try? await APIClient.shared.json(url, ttl: 300), let results = root.object?["results"]?.array else { return [] } return results.compactMap { r -> KAItem? in guard let o = r.object, let id = o.str("id"), let lat = o.num("lat"), let lng = o.num("lng"), let est = o.num("est2026"), est > 0 else { return nil } let apt = o.str("apt").flatMap { $0.isEmpty ? nil : $0 } return KAItem( id: "vp:\(id)", universeID: "vrai-prix", title: [o.str("adresse"), apt.map { "app. \($0)" }] .compactMap { $0 }.joined(separator: " "), subtitle: o.str("typeProp"), priceLabel: "\(est.compact)$", city: o.str("municipalite"), url: URL(string: "https://www.vrai-prix.com/estimation/\(id)"), imageURL: nil, latitude: lat, longitude: lng, detail: nil, facts: [.init(label: "Estimation Vrai-Prix 2026", value: est.money0)] ) } } /// Total « en direct » depuis /api/stats (clé selon l'univers, chemins a.b acceptés) static func liveTotal(_ u: Universe) async -> Int? { let path = u.id == "trouve-ka" ? "/api/status" : "/api/stats" guard let url = URL(string: "https://\(u.domain)\(path)"), let root = try? await APIClient.shared.json(url, ttl: 300) else { return nil } for key in u.statTotalKeys { var cur: JSONValue? = root for part in key.split(separator: ".") { cur = cur?.object?[String(part)] } if let n = cur?.number { return Int(n) } } return nil } } // MARK: - KA Agent (SSE) struct AgentEvent { let kind: Kind; enum Kind { case delta(String), tool(String), done, error(String) } } enum AgentService { static let endpoint = URL(string: "https://www.api-ka.com/api/agent/chat")! static func stream(site: String, messages: [[String: String]]) -> AsyncThrowingStream { AsyncThrowingStream { continuation in let task = Task { var req = URLRequest(url: endpoint) req.httpMethod = "POST" req.setValue("application/json", forHTTPHeaderField: "Content-Type") req.timeoutInterval = 90 req.httpBody = try JSONSerialization.data(withJSONObject: ["site": site, "messages": messages]) let (bytes, resp) = try await URLSession.shared.bytes(for: req) guard (resp as? HTTPURLResponse)?.statusCode == 200 else { throw URLError(.badServerResponse) } var event = "" for try await line in bytes.lines { if line.hasPrefix("event: ") { event = String(line.dropFirst(7)) } else if line.hasPrefix("data: ") { let data = Data(line.dropFirst(6).utf8) let obj = (try? JSONSerialization.jsonObject(with: data) as? [String: Any]) ?? [:] switch event { case "delta": if let t = obj["text"] as? String { continuation.yield(.init(kind: .delta(t))) } case "tool": continuation.yield(.init(kind: .tool(obj["name"] as? String ?? "recherche"))) case "done": continuation.yield(.init(kind: .done)); continuation.finish(); return case "error": continuation.yield(.init(kind: .error(obj["message"] as? String ?? "erreur"))) default: break } } } continuation.finish() } continuation.onTermination = { _ in task.cancel() } } } }