import CryptoKit
import Foundation

/// A small Piggy client for Swift (macOS 12 or later), Foundation and CryptoKit only.
/// Copy this file into your app. Over https it trusts Piggy's own
/// certificate by its SHA-256 fingerprint, the one the person copies from
/// the Piggy window (Connections, Copy next to the certificate).
///
///     let piggy = try PiggyClient(baseURL: URL(string: "https://127.0.0.1:8379")!,
///                                 key: key, fingerprint: "AB:CD:...")
///     let answer = try await piggy.infer("Say hello in five words.", model: "haiku")
public final class PiggyClient {
    public struct Failure: Error, CustomStringConvertible {
        public let status: Int        // 0: no answer at all
        public let message: String
        public var description: String { "Piggy answered \(status): \(message)" }
    }

    /// Seconds to wait before retrying, by status. 400 and 401 are never
    /// retried; 429 means come back in minutes.
    private static let retryAfter: [Int: Double] = [0: 5, 500: 5, 502: 30, 503: 3, 504: 5]

    private let baseURL: URL
    private let key: String
    private let session: URLSession

    /// fingerprint: required for an https address, not allowed for http.
    public init(baseURL: URL, key: String, fingerprint: String?) throws {
        let secure = baseURL.scheme == "https"
        if secure && fingerprint == nil {
            throw Failure(status: 0, message: "an https address needs Piggy's certificate fingerprint")
        }
        if !secure && fingerprint != nil {
            throw Failure(status: 0, message: "a fingerprint is only for an https address")
        }
        self.baseURL = baseURL
        self.key = key
        session = URLSession(configuration: .ephemeral, delegate: PinnedTrust(fingerprint: fingerprint),
                             delegateQueue: nil)
    }

    deinit { session.finishTasksAndInvalidate() }

    public func infer(_ prompt: String, model: String, schema: [String: Any]? = nil,
                      system: String? = nil, timeout: TimeInterval = 30, attempts: Int = 3) async throws -> Any {
        var body: [String: Any] = ["prompt": prompt, "model": model, "timeout_s": timeout]
        if let schema = schema { body["schema"] = schema }
        if let system = system { body["system"] = system }
        for attempt in 1...attempts {
            let (status, answer) = await call("POST", "infer", body: body, timeout: timeout + 5)
            if status == 200 {
                if schema != nil, answer["structured"] as? Bool != true {
                    throw Failure(status: status, message: "the answer did not match the schema")
                }
                return answer["output"] ?? NSNull()
            }
            guard let wait = Self.retryAfter[status], attempt < attempts else {
                throw Failure(status: status, message: answer["error"] as? String ?? "")
            }
            try await Task.sleep(nanoseconds: UInt64(wait * Double(attempt) * 1_000_000_000))
        }
        throw Failure(status: 0, message: "no attempts made")
    }

    public func health() async throws -> [String: Any] {
        let (status, answer) = await call("GET", "health", body: nil, timeout: 5)
        guard status == 200 else { throw Failure(status: status, message: answer["error"] as? String ?? "") }
        return answer
    }

    /// (status, JSON body); status 0 and an "error" when Piggy gave no answer.
    private func call(_ method: String, _ path: String, body: [String: Any]?,
                      timeout: TimeInterval) async -> (Int, [String: Any]) {
        var request = URLRequest(url: baseURL.appendingPathComponent(path), timeoutInterval: timeout)
        request.httpMethod = method
        request.setValue("Bearer \(key)", forHTTPHeaderField: "Authorization")
        if let body = body {
            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.httpBody = try? JSONSerialization.data(withJSONObject: body)
        }
        do {
            let (data, response) = try await session.data(for: request)
            let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
                ?? ["error": String(decoding: data.prefix(200), as: UTF8.self)]
            return ((response as? HTTPURLResponse)?.statusCode ?? 0, json)
        } catch {
            return (0, ["error": "no answer from Piggy: \(error.localizedDescription)"])
        }
    }
}

/// Accepts the server only when its certificate is exactly the one fingerprinted.
private final class PinnedTrust: NSObject, URLSessionDelegate {
    private let fingerprint: String?

    init(fingerprint: String?) {
        self.fingerprint = fingerprint?.uppercased().trimmingCharacters(in: .whitespacesAndNewlines)
    }

    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge,
                    completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        guard challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
              let trust = challenge.protectionSpace.serverTrust,
              let leaf = (SecTrustCopyCertificateChain(trust) as? [SecCertificate])?.first,
              let expected = fingerprint
        else { return completionHandler(.cancelAuthenticationChallenge, nil) }
        let presented = SHA256.hash(data: SecCertificateCopyData(leaf) as Data)
            .map { String(format: "%02X", $0) }.joined(separator: ":")
        completionHandler(presented == expected ? .useCredential : .cancelAuthenticationChallenge,
                          presented == expected ? URLCredential(trust: trust) : nil)
    }
}
