cooklang-import 0.9.8

A tool for importing recipes into Cooklang format
Documentation
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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
// This file was autogenerated by some hot garbage in the `uniffi` crate.
// Trust me, you don't want to mess with it!

// swiftlint:disable all
import Foundation

// Depending on the consumer's build setup, the low-level FFI code
// might be in a separate module, or it might be compiled inline into
// this module. This is a bit of light hackery to work with both.
#if canImport(CooklangImportFFI)
    import CooklangImportFFI
#endif

private extension RustBuffer {
    /// Allocate a new buffer, copying the contents of a `UInt8` array.
    init(bytes: [UInt8]) {
        let rbuf = bytes.withUnsafeBufferPointer { ptr in
            RustBuffer.from(ptr)
        }
        self.init(capacity: rbuf.capacity, len: rbuf.len, data: rbuf.data)
    }

    static func empty() -> RustBuffer {
        RustBuffer(capacity: 0, len: 0, data: nil)
    }

    static func from(_ ptr: UnsafeBufferPointer<UInt8>) -> RustBuffer {
        try! rustCall { ffi_cooklang_import_rustbuffer_from_bytes(ForeignBytes(bufferPointer: ptr), $0) }
    }

    /// Frees the buffer in place.
    /// The buffer must not be used after this is called.
    func deallocate() {
        try! rustCall { ffi_cooklang_import_rustbuffer_free(self, $0) }
    }
}

private extension ForeignBytes {
    init(bufferPointer: UnsafeBufferPointer<UInt8>) {
        self.init(len: Int32(bufferPointer.count), data: bufferPointer.baseAddress)
    }
}

// For every type used in the interface, we provide helper methods for conveniently
// lifting and lowering that type from C-compatible data, and for reading and writing
// values of that type in a buffer.

// Helper classes/extensions that don't change.
// Someday, this will be in a library of its own.

private extension Data {
    init(rustBuffer: RustBuffer) {
        self.init(
            bytesNoCopy: rustBuffer.data!,
            count: Int(rustBuffer.len),
            deallocator: .none
        )
    }
}

// Define reader functionality.  Normally this would be defined in a class or
// struct, but we use standalone functions instead in order to make external
// types work.
//
// With external types, one swift source file needs to be able to call the read
// method on another source file's FfiConverter, but then what visibility
// should Reader have?
// - If Reader is fileprivate, then this means the read() must also
//   be fileprivate, which doesn't work with external types.
// - If Reader is internal/public, we'll get compile errors since both source
//   files will try define the same type.
//
// Instead, the read() method and these helper functions input a tuple of data

private func createReader(data: Data) -> (data: Data, offset: Data.Index) {
    (data: data, offset: 0)
}

/// Reads an integer at the current offset, in big-endian order, and advances
/// the offset on success. Throws if reading the integer would move the
/// offset past the end of the buffer.
private func readInt<T: FixedWidthInteger>(_ reader: inout (data: Data, offset: Data.Index)) throws -> T {
    let range = reader.offset ..< reader.offset + MemoryLayout<T>.size
    guard reader.data.count >= range.upperBound else {
        throw UniffiInternalError.bufferOverflow
    }
    if T.self == UInt8.self {
        let value = reader.data[reader.offset]
        reader.offset += 1
        return value as! T
    }
    var value: T = 0
    let _ = withUnsafeMutableBytes(of: &value) { reader.data.copyBytes(to: $0, from: range) }
    reader.offset = range.upperBound
    return value.bigEndian
}

/// Reads an arbitrary number of bytes, to be used to read
/// raw bytes, this is useful when lifting strings
private func readBytes(_ reader: inout (data: Data, offset: Data.Index), count: Int) throws -> [UInt8] {
    let range = reader.offset ..< (reader.offset + count)
    guard reader.data.count >= range.upperBound else {
        throw UniffiInternalError.bufferOverflow
    }
    var value = [UInt8](repeating: 0, count: count)
    value.withUnsafeMutableBufferPointer { buffer in
        reader.data.copyBytes(to: buffer, from: range)
    }
    reader.offset = range.upperBound
    return value
}

/// Reads a float at the current offset.
private func readFloat(_ reader: inout (data: Data, offset: Data.Index)) throws -> Float {
    return try Float(bitPattern: readInt(&reader))
}

/// Reads a float at the current offset.
private func readDouble(_ reader: inout (data: Data, offset: Data.Index)) throws -> Double {
    return try Double(bitPattern: readInt(&reader))
}

/// Indicates if the offset has reached the end of the buffer.
private func hasRemaining(_ reader: (data: Data, offset: Data.Index)) -> Bool {
    return reader.offset < reader.data.count
}

// Define writer functionality.  Normally this would be defined in a class or
// struct, but we use standalone functions instead in order to make external
// types work.  See the above discussion on Readers for details.

private func createWriter() -> [UInt8] {
    return []
}

private func writeBytes<S: Sequence>(_ writer: inout [UInt8], _ byteArr: S) where S.Element == UInt8 {
    writer.append(contentsOf: byteArr)
}

/// Writes an integer in big-endian order.
///
/// Warning: make sure what you are trying to write
/// is in the correct type!
private func writeInt<T: FixedWidthInteger>(_ writer: inout [UInt8], _ value: T) {
    var value = value.bigEndian
    withUnsafeBytes(of: &value) { writer.append(contentsOf: $0) }
}

private func writeFloat(_ writer: inout [UInt8], _ value: Float) {
    writeInt(&writer, value.bitPattern)
}

private func writeDouble(_ writer: inout [UInt8], _ value: Double) {
    writeInt(&writer, value.bitPattern)
}

/// Protocol for types that transfer other types across the FFI. This is
/// analogous to the Rust trait of the same name.
private protocol FfiConverter {
    associatedtype FfiType
    associatedtype SwiftType

    static func lift(_ value: FfiType) throws -> SwiftType
    static func lower(_ value: SwiftType) -> FfiType
    static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType
    static func write(_ value: SwiftType, into buf: inout [UInt8])
}

/// Types conforming to `Primitive` pass themselves directly over the FFI.
private protocol FfiConverterPrimitive: FfiConverter where FfiType == SwiftType {}

extension FfiConverterPrimitive {
    #if swift(>=5.8)
        @_documentation(visibility: private)
    #endif
    public static func lift(_ value: FfiType) throws -> SwiftType {
        return value
    }

    #if swift(>=5.8)
        @_documentation(visibility: private)
    #endif
    public static func lower(_ value: SwiftType) -> FfiType {
        return value
    }
}

/// Types conforming to `FfiConverterRustBuffer` lift and lower into a `RustBuffer`.
/// Used for complex types where it's hard to write a custom lift/lower.
private protocol FfiConverterRustBuffer: FfiConverter where FfiType == RustBuffer {}

extension FfiConverterRustBuffer {
    #if swift(>=5.8)
        @_documentation(visibility: private)
    #endif
    public static func lift(_ buf: RustBuffer) throws -> SwiftType {
        var reader = createReader(data: Data(rustBuffer: buf))
        let value = try read(from: &reader)
        if hasRemaining(reader) {
            throw UniffiInternalError.incompleteData
        }
        buf.deallocate()
        return value
    }

    #if swift(>=5.8)
        @_documentation(visibility: private)
    #endif
    public static func lower(_ value: SwiftType) -> RustBuffer {
        var writer = createWriter()
        write(value, into: &writer)
        return RustBuffer(bytes: writer)
    }
}

/// An error type for FFI errors. These errors occur at the UniFFI level, not
/// the library level.
private enum UniffiInternalError: LocalizedError {
    case bufferOverflow
    case incompleteData
    case unexpectedOptionalTag
    case unexpectedEnumCase
    case unexpectedNullPointer
    case unexpectedRustCallStatusCode
    case unexpectedRustCallError
    case unexpectedStaleHandle
    case rustPanic(_ message: String)

    var errorDescription: String? {
        switch self {
        case .bufferOverflow: return "Reading the requested value would read past the end of the buffer"
        case .incompleteData: return "The buffer still has data after lifting its containing value"
        case .unexpectedOptionalTag: return "Unexpected optional tag; should be 0 or 1"
        case .unexpectedEnumCase: return "Raw enum value doesn't match any cases"
        case .unexpectedNullPointer: return "Raw pointer value was null"
        case .unexpectedRustCallStatusCode: return "Unexpected RustCallStatus code"
        case .unexpectedRustCallError: return "CALL_ERROR but no errorClass specified"
        case .unexpectedStaleHandle: return "The object in the handle map has been dropped already"
        case let .rustPanic(message): return message
        }
    }
}

private extension NSLock {
    func withLock<T>(f: () throws -> T) rethrows -> T {
        lock()
        defer { self.unlock() }
        return try f()
    }
}

private let CALL_SUCCESS: Int8 = 0
private let CALL_ERROR: Int8 = 1
private let CALL_UNEXPECTED_ERROR: Int8 = 2
private let CALL_CANCELLED: Int8 = 3

private extension RustCallStatus {
    init() {
        self.init(
            code: CALL_SUCCESS,
            errorBuf: RustBuffer(
                capacity: 0,
                len: 0,
                data: nil
            )
        )
    }
}

private func rustCall<T>(_ callback: (UnsafeMutablePointer<RustCallStatus>) -> T) throws -> T {
    let neverThrow: ((RustBuffer) throws -> Never)? = nil
    return try makeRustCall(callback, errorHandler: neverThrow)
}

private func rustCallWithError<T, E: Swift.Error>(
    _ errorHandler: @escaping (RustBuffer) throws -> E,
    _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T
) throws -> T {
    try makeRustCall(callback, errorHandler: errorHandler)
}

private func makeRustCall<T, E: Swift.Error>(
    _ callback: (UnsafeMutablePointer<RustCallStatus>) -> T,
    errorHandler: ((RustBuffer) throws -> E)?
) throws -> T {
    uniffiEnsureInitialized()
    var callStatus = RustCallStatus()
    let returnedVal = callback(&callStatus)
    try uniffiCheckCallStatus(callStatus: callStatus, errorHandler: errorHandler)
    return returnedVal
}

private func uniffiCheckCallStatus<E: Swift.Error>(
    callStatus: RustCallStatus,
    errorHandler: ((RustBuffer) throws -> E)?
) throws {
    switch callStatus.code {
    case CALL_SUCCESS:
        return

    case CALL_ERROR:
        if let errorHandler = errorHandler {
            throw try errorHandler(callStatus.errorBuf)
        } else {
            callStatus.errorBuf.deallocate()
            throw UniffiInternalError.unexpectedRustCallError
        }

    case CALL_UNEXPECTED_ERROR:
        // When the rust code sees a panic, it tries to construct a RustBuffer
        // with the message.  But if that code panics, then it just sends back
        // an empty buffer.
        if callStatus.errorBuf.len > 0 {
            throw try UniffiInternalError.rustPanic(FfiConverterString.lift(callStatus.errorBuf))
        } else {
            callStatus.errorBuf.deallocate()
            throw UniffiInternalError.rustPanic("Rust panic")
        }

    case CALL_CANCELLED:
        fatalError("Cancellation not supported yet")

    default:
        throw UniffiInternalError.unexpectedRustCallStatusCode
    }
}

private func uniffiTraitInterfaceCall<T>(
    callStatus: UnsafeMutablePointer<RustCallStatus>,
    makeCall: () throws -> T,
    writeReturn: (T) -> Void
) {
    do {
        try writeReturn(makeCall())
    } catch {
        callStatus.pointee.code = CALL_UNEXPECTED_ERROR
        callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
    }
}

private func uniffiTraitInterfaceCallWithError<T, E>(
    callStatus: UnsafeMutablePointer<RustCallStatus>,
    makeCall: () throws -> T,
    writeReturn: (T) -> Void,
    lowerError: (E) -> RustBuffer
) {
    do {
        try writeReturn(makeCall())
    } catch let error as E {
        callStatus.pointee.code = CALL_ERROR
        callStatus.pointee.errorBuf = lowerError(error)
    } catch {
        callStatus.pointee.code = CALL_UNEXPECTED_ERROR
        callStatus.pointee.errorBuf = FfiConverterString.lower(String(describing: error))
    }
}

private class UniffiHandleMap<T> {
    private var map: [UInt64: T] = [:]
    private let lock = NSLock()
    private var currentHandle: UInt64 = 1

    func insert(obj: T) -> UInt64 {
        lock.withLock {
            let handle = currentHandle
            currentHandle += 1
            map[handle] = obj
            return handle
        }
    }

    func get(handle: UInt64) throws -> T {
        try lock.withLock {
            guard let obj = map[handle] else {
                throw UniffiInternalError.unexpectedStaleHandle
            }
            return obj
        }
    }

    @discardableResult
    func remove(handle: UInt64) throws -> T {
        try lock.withLock {
            guard let obj = map.removeValue(forKey: handle) else {
                throw UniffiInternalError.unexpectedStaleHandle
            }
            return obj
        }
    }

    var count: Int {
        map.count
    }
}

// Public interface members begin here.

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
private struct FfiConverterUInt64: FfiConverterPrimitive {
    typealias FfiType = UInt64
    typealias SwiftType = UInt64

    static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> UInt64 {
        return try lift(readInt(&buf))
    }

    static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        writeInt(&buf, lower(value))
    }
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
private struct FfiConverterBool: FfiConverter {
    typealias FfiType = Int8
    typealias SwiftType = Bool

    static func lift(_ value: Int8) throws -> Bool {
        return value != 0
    }

    static func lower(_ value: Bool) -> Int8 {
        return value ? 1 : 0
    }

    static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Bool {
        return try lift(readInt(&buf))
    }

    static func write(_ value: Bool, into buf: inout [UInt8]) {
        writeInt(&buf, lower(value))
    }
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
private struct FfiConverterString: FfiConverter {
    typealias SwiftType = String
    typealias FfiType = RustBuffer

    static func lift(_ value: RustBuffer) throws -> String {
        defer {
            value.deallocate()
        }
        if value.data == nil {
            return String()
        }
        let bytes = UnsafeBufferPointer<UInt8>(start: value.data!, count: Int(value.len))
        return String(bytes: bytes, encoding: String.Encoding.utf8)!
    }

    static func lower(_ value: String) -> RustBuffer {
        return value.utf8CString.withUnsafeBufferPointer { ptr in
            // The swift string gives us int8_t, we want uint8_t.
            ptr.withMemoryRebound(to: UInt8.self) { ptr in
                // The swift string gives us a trailing null byte, we don't want it.
                let buf = UnsafeBufferPointer(rebasing: ptr.prefix(upTo: ptr.count - 1))
                return RustBuffer.from(buf)
            }
        }
    }

    static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> String {
        let len: Int32 = try readInt(&buf)
        return try String(bytes: readBytes(&buf, count: Int(len)), encoding: String.Encoding.utf8)!
    }

    static func write(_ value: String, into buf: inout [UInt8]) {
        let len = Int32(value.utf8.count)
        writeInt(&buf, len)
        writeBytes(&buf, value.utf8)
    }
}

/**
 * Configuration for importing recipes
 */
public struct FfiImportConfig {
    /**
     * Optional LLM provider (uses default if not specified)
     */
    public let provider: FfiLlmProvider?
    /**
     * Optional API key (uses environment variable if not specified)
     */
    public let apiKey: String?
    /**
     * Optional model name (uses provider default if not specified)
     */
    public let model: String?
    /**
     * Optional timeout in seconds (uses default if not specified)
     */
    public let timeoutSeconds: UInt64?
    /**
     * If true, only extract recipe without converting to Cooklang
     */
    public let extractOnly: Bool

    /// Default memberwise initializers are never public by default, so we
    /// declare one manually.
    public init(
        /* 
         * Optional LLM provider (uses default if not specified)
         */ provider: FfiLlmProvider?,
        /* 
            * Optional API key (uses environment variable if not specified)
            */ apiKey: String?,
        /* 
            * Optional model name (uses provider default if not specified)
            */ model: String?,
        /* 
            * Optional timeout in seconds (uses default if not specified)
            */ timeoutSeconds: UInt64?,
        /* 
            * If true, only extract recipe without converting to Cooklang
            */ extractOnly: Bool
    ) {
        self.provider = provider
        self.apiKey = apiKey
        self.model = model
        self.timeoutSeconds = timeoutSeconds
        self.extractOnly = extractOnly
    }
}

extension FfiImportConfig: Equatable, Hashable {
    public static func == (lhs: FfiImportConfig, rhs: FfiImportConfig) -> Bool {
        if lhs.provider != rhs.provider {
            return false
        }
        if lhs.apiKey != rhs.apiKey {
            return false
        }
        if lhs.model != rhs.model {
            return false
        }
        if lhs.timeoutSeconds != rhs.timeoutSeconds {
            return false
        }
        if lhs.extractOnly != rhs.extractOnly {
            return false
        }
        return true
    }

    public func hash(into hasher: inout Hasher) {
        hasher.combine(provider)
        hasher.combine(apiKey)
        hasher.combine(model)
        hasher.combine(timeoutSeconds)
        hasher.combine(extractOnly)
    }
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
public struct FfiConverterTypeFfiImportConfig: FfiConverterRustBuffer {
    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiImportConfig {
        return
            try FfiImportConfig(
                provider: FfiConverterOptionTypeFfiLlmProvider.read(from: &buf),
                apiKey: FfiConverterOptionString.read(from: &buf),
                model: FfiConverterOptionString.read(from: &buf),
                timeoutSeconds: FfiConverterOptionUInt64.read(from: &buf),
                extractOnly: FfiConverterBool.read(from: &buf)
            )
    }

    public static func write(_ value: FfiImportConfig, into buf: inout [UInt8]) {
        FfiConverterOptionTypeFfiLlmProvider.write(value.provider, into: &buf)
        FfiConverterOptionString.write(value.apiKey, into: &buf)
        FfiConverterOptionString.write(value.model, into: &buf)
        FfiConverterOptionUInt64.write(value.timeoutSeconds, into: &buf)
        FfiConverterBool.write(value.extractOnly, into: &buf)
    }
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiImportConfig_lift(_ buf: RustBuffer) throws -> FfiImportConfig {
    return try FfiConverterTypeFfiImportConfig.lift(buf)
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiImportConfig_lower(_ value: FfiImportConfig) -> RustBuffer {
    return FfiConverterTypeFfiImportConfig.lower(value)
}

/**
 * FFI-compatible recipe components structure
 */
public struct FfiRecipeComponents {
    /**
     * Recipe text (ingredients + instructions)
     */
    public let text: String
    /**
     * YAML-formatted metadata (without --- delimiters)
     */
    public let metadata: String
    /**
     * Recipe name/title
     */
    public let name: String

    /// Default memberwise initializers are never public by default, so we
    /// declare one manually.
    public init(
        /* 
         * Recipe text (ingredients + instructions)
         */ text: String,
        /* 
            * YAML-formatted metadata (without --- delimiters)
            */ metadata: String,
        /* 
            * Recipe name/title
            */ name: String
    ) {
        self.text = text
        self.metadata = metadata
        self.name = name
    }
}

extension FfiRecipeComponents: Equatable, Hashable {
    public static func == (lhs: FfiRecipeComponents, rhs: FfiRecipeComponents) -> Bool {
        if lhs.text != rhs.text {
            return false
        }
        if lhs.metadata != rhs.metadata {
            return false
        }
        if lhs.name != rhs.name {
            return false
        }
        return true
    }

    public func hash(into hasher: inout Hasher) {
        hasher.combine(text)
        hasher.combine(metadata)
        hasher.combine(name)
    }
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
public struct FfiConverterTypeFfiRecipeComponents: FfiConverterRustBuffer {
    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiRecipeComponents {
        return
            try FfiRecipeComponents(
                text: FfiConverterString.read(from: &buf),
                metadata: FfiConverterString.read(from: &buf),
                name: FfiConverterString.read(from: &buf)
            )
    }

    public static func write(_ value: FfiRecipeComponents, into buf: inout [UInt8]) {
        FfiConverterString.write(value.text, into: &buf)
        FfiConverterString.write(value.metadata, into: &buf)
        FfiConverterString.write(value.name, into: &buf)
    }
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiRecipeComponents_lift(_ buf: RustBuffer) throws -> FfiRecipeComponents {
    return try FfiConverterTypeFfiRecipeComponents.lift(buf)
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiRecipeComponents_lower(_ value: FfiRecipeComponents) -> RustBuffer {
    return FfiConverterTypeFfiRecipeComponents.lower(value)
}

/**
 * FFI-compatible error type
 */
public enum FfiImportError {
    /**
     * Failed to fetch recipe from URL
     */
    case FetchError(reason: String)
    /**
     * Failed to parse recipe from webpage
     */
    case ParseError(reason: String)
    /**
     * No extractor could successfully parse the recipe
     */
    case NoExtractorMatched(reason: String)
    /**
     * Failed to convert recipe to Cooklang format
     */
    case ConversionError(reason: String)
    /**
     * Invalid input provided
     */
    case InvalidInput(reason: String)
    /**
     * Builder configuration error
     */
    case BuilderError(reason: String)
    /**
     * Configuration error
     */
    case ConfigError(reason: String)
    /**
     * Runtime error (tokio)
     */
    case RuntimeError(reason: String)
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
public struct FfiConverterTypeFfiImportError: FfiConverterRustBuffer {
    typealias SwiftType = FfiImportError

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiImportError {
        let variant: Int32 = try readInt(&buf)
        switch variant {
        case 1: return try .FetchError(
                reason: FfiConverterString.read(from: &buf)
            )
        case 2: return try .ParseError(
                reason: FfiConverterString.read(from: &buf)
            )
        case 3: return try .NoExtractorMatched(
                reason: FfiConverterString.read(from: &buf)
            )
        case 4: return try .ConversionError(
                reason: FfiConverterString.read(from: &buf)
            )
        case 5: return try .InvalidInput(
                reason: FfiConverterString.read(from: &buf)
            )
        case 6: return try .BuilderError(
                reason: FfiConverterString.read(from: &buf)
            )
        case 7: return try .ConfigError(
                reason: FfiConverterString.read(from: &buf)
            )
        case 8: return try .RuntimeError(
                reason: FfiConverterString.read(from: &buf)
            )
        default: throw UniffiInternalError.unexpectedEnumCase
        }
    }

    public static func write(_ value: FfiImportError, into buf: inout [UInt8]) {
        switch value {
        case let .FetchError(reason):
            writeInt(&buf, Int32(1))
            FfiConverterString.write(reason, into: &buf)

        case let .ParseError(reason):
            writeInt(&buf, Int32(2))
            FfiConverterString.write(reason, into: &buf)

        case let .NoExtractorMatched(reason):
            writeInt(&buf, Int32(3))
            FfiConverterString.write(reason, into: &buf)

        case let .ConversionError(reason):
            writeInt(&buf, Int32(4))
            FfiConverterString.write(reason, into: &buf)

        case let .InvalidInput(reason):
            writeInt(&buf, Int32(5))
            FfiConverterString.write(reason, into: &buf)

        case let .BuilderError(reason):
            writeInt(&buf, Int32(6))
            FfiConverterString.write(reason, into: &buf)

        case let .ConfigError(reason):
            writeInt(&buf, Int32(7))
            FfiConverterString.write(reason, into: &buf)

        case let .RuntimeError(reason):
            writeInt(&buf, Int32(8))
            FfiConverterString.write(reason, into: &buf)
        }
    }
}

extension FfiImportError: Equatable, Hashable {}

extension FfiImportError: Foundation.LocalizedError {
    public var errorDescription: String? {
        String(reflecting: self)
    }
}

// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
/* 
 * FFI-compatible import result
 */

public enum FfiImportResult {
    /**
     * Recipe converted to Cooklang format
     */
    case cooklang(content: String)
    /**
     * Recipe components extracted but not converted
     */
    case components(components: FfiRecipeComponents)
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
public struct FfiConverterTypeFfiImportResult: FfiConverterRustBuffer {
    typealias SwiftType = FfiImportResult

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiImportResult {
        let variant: Int32 = try readInt(&buf)
        switch variant {
        case 1: return try .cooklang(content: FfiConverterString.read(from: &buf))

        case 2: return try .components(components: FfiConverterTypeFfiRecipeComponents.read(from: &buf))

        default: throw UniffiInternalError.unexpectedEnumCase
        }
    }

    public static func write(_ value: FfiImportResult, into buf: inout [UInt8]) {
        switch value {
        case let .cooklang(content):
            writeInt(&buf, Int32(1))
            FfiConverterString.write(content, into: &buf)

        case let .components(components):
            writeInt(&buf, Int32(2))
            FfiConverterTypeFfiRecipeComponents.write(components, into: &buf)
        }
    }
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiImportResult_lift(_ buf: RustBuffer) throws -> FfiImportResult {
    return try FfiConverterTypeFfiImportResult.lift(buf)
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiImportResult_lower(_ value: FfiImportResult) -> RustBuffer {
    return FfiConverterTypeFfiImportResult.lower(value)
}

extension FfiImportResult: Equatable, Hashable {}

// Note that we don't yet support `indirect` for enums.
// See https://github.com/mozilla/uniffi-rs/issues/396 for further discussion.
/* 
 * FFI-compatible LLM provider enum
 */

public enum FfiLlmProvider {
    case openAi
    case anthropic
    case google
    case azureOpenAi
    case ollama
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
public struct FfiConverterTypeFfiLlmProvider: FfiConverterRustBuffer {
    typealias SwiftType = FfiLlmProvider

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> FfiLlmProvider {
        let variant: Int32 = try readInt(&buf)
        switch variant {
        case 1: return .openAi

        case 2: return .anthropic

        case 3: return .google

        case 4: return .azureOpenAi

        case 5: return .ollama

        default: throw UniffiInternalError.unexpectedEnumCase
        }
    }

    public static func write(_ value: FfiLlmProvider, into buf: inout [UInt8]) {
        switch value {
        case .openAi:
            writeInt(&buf, Int32(1))

        case .anthropic:
            writeInt(&buf, Int32(2))

        case .google:
            writeInt(&buf, Int32(3))

        case .azureOpenAi:
            writeInt(&buf, Int32(4))

        case .ollama:
            writeInt(&buf, Int32(5))
        }
    }
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiLlmProvider_lift(_ buf: RustBuffer) throws -> FfiLlmProvider {
    return try FfiConverterTypeFfiLlmProvider.lift(buf)
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
public func FfiConverterTypeFfiLlmProvider_lower(_ value: FfiLlmProvider) -> RustBuffer {
    return FfiConverterTypeFfiLlmProvider.lower(value)
}

extension FfiLlmProvider: Equatable, Hashable {}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
private struct FfiConverterOptionUInt64: FfiConverterRustBuffer {
    typealias SwiftType = UInt64?

    static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        guard let value = value else {
            writeInt(&buf, Int8(0))
            return
        }
        writeInt(&buf, Int8(1))
        FfiConverterUInt64.write(value, into: &buf)
    }

    static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        switch try readInt(&buf) as Int8 {
        case 0: return nil
        case 1: return try FfiConverterUInt64.read(from: &buf)
        default: throw UniffiInternalError.unexpectedOptionalTag
        }
    }
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
private struct FfiConverterOptionString: FfiConverterRustBuffer {
    typealias SwiftType = String?

    static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        guard let value = value else {
            writeInt(&buf, Int8(0))
            return
        }
        writeInt(&buf, Int8(1))
        FfiConverterString.write(value, into: &buf)
    }

    static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        switch try readInt(&buf) as Int8 {
        case 0: return nil
        case 1: return try FfiConverterString.read(from: &buf)
        default: throw UniffiInternalError.unexpectedOptionalTag
        }
    }
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
private struct FfiConverterOptionTypeFfiImportConfig: FfiConverterRustBuffer {
    typealias SwiftType = FfiImportConfig?

    static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        guard let value = value else {
            writeInt(&buf, Int8(0))
            return
        }
        writeInt(&buf, Int8(1))
        FfiConverterTypeFfiImportConfig.write(value, into: &buf)
    }

    static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        switch try readInt(&buf) as Int8 {
        case 0: return nil
        case 1: return try FfiConverterTypeFfiImportConfig.read(from: &buf)
        default: throw UniffiInternalError.unexpectedOptionalTag
        }
    }
}

#if swift(>=5.8)
    @_documentation(visibility: private)
#endif
private struct FfiConverterOptionTypeFfiLlmProvider: FfiConverterRustBuffer {
    typealias SwiftType = FfiLlmProvider?

    static func write(_ value: SwiftType, into buf: inout [UInt8]) {
        guard let value = value else {
            writeInt(&buf, Int8(0))
            return
        }
        writeInt(&buf, Int8(1))
        FfiConverterTypeFfiLlmProvider.write(value, into: &buf)
    }

    static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> SwiftType {
        switch try readInt(&buf) as Int8 {
        case 0: return nil
        case 1: return try FfiConverterTypeFfiLlmProvider.read(from: &buf)
        default: throw UniffiInternalError.unexpectedOptionalTag
        }
    }
}

/**
 * Convert an image to Cooklang format using OCR
 *
 * # Arguments
 * * `image_path` - Path to the image file
 * * `config` - Optional configuration for the conversion
 *
 * # Returns
 * A string containing the recipe in Cooklang format
 */
public func convertImageToCooklang(imagePath: String, config: FfiImportConfig?) throws -> String {
    return try FfiConverterString.lift(rustCallWithError(FfiConverterTypeFfiImportError.lift) {
        uniffi_cooklang_import_fn_func_convert_image_to_cooklang(
            FfiConverterString.lower(imagePath),
            FfiConverterOptionTypeFfiImportConfig.lower(config), $0
        )
    })
}

/**
 * Convert plain text to Cooklang format
 *
 * # Arguments
 * * `text` - The recipe text in plain format
 * * `config` - Optional configuration for the conversion
 *
 * # Returns
 * A string containing the recipe in Cooklang format
 */
public func convertTextToCooklang(text: String, config: FfiImportConfig?) throws -> String {
    return try FfiConverterString.lift(rustCallWithError(FfiConverterTypeFfiImportError.lift) {
        uniffi_cooklang_import_fn_func_convert_text_to_cooklang(
            FfiConverterString.lower(text),
            FfiConverterOptionTypeFfiImportConfig.lower(config), $0
        )
    })
}

/**
 * Extract recipe components from a URL without converting to Cooklang format
 *
 * # Arguments
 * * `url` - The URL of the recipe webpage
 * * `timeout_seconds` - Optional timeout in seconds
 *
 * # Returns
 * An `FfiRecipeComponents` struct containing the extracted recipe data
 */
public func extractRecipeFromUrl(url: String, timeoutSeconds: UInt64?) throws -> FfiRecipeComponents {
    return try FfiConverterTypeFfiRecipeComponents.lift(rustCallWithError(FfiConverterTypeFfiImportError.lift) {
        uniffi_cooklang_import_fn_func_extract_recipe_from_url(
            FfiConverterString.lower(url),
            FfiConverterOptionUInt64.lower(timeoutSeconds), $0
        )
    })
}

/**
 * Get the library version
 */
public func getVersion() -> String {
    return try! FfiConverterString.lift(try! rustCall {
        uniffi_cooklang_import_fn_func_get_version($0)
    })
}

/**
 * Import a recipe from a URL
 *
 * # Arguments
 * * `url` - The URL of the recipe webpage
 * * `config` - Optional configuration for the import
 *
 * # Returns
 * An `FfiImportResult` containing either Cooklang text or a Recipe struct
 */
public func importFromUrl(url: String, config: FfiImportConfig?) throws -> FfiImportResult {
    return try FfiConverterTypeFfiImportResult.lift(rustCallWithError(FfiConverterTypeFfiImportError.lift) {
        uniffi_cooklang_import_fn_func_import_from_url(
            FfiConverterString.lower(url),
            FfiConverterOptionTypeFfiImportConfig.lower(config), $0
        )
    })
}

/**
 * Check if a provider is available (has required environment variables)
 */
public func isProviderAvailable(provider: FfiLlmProvider) -> Bool {
    return try! FfiConverterBool.lift(try! rustCall {
        uniffi_cooklang_import_fn_func_is_provider_available(
            FfiConverterTypeFfiLlmProvider.lower(provider), $0
        )
    })
}

/**
 * Simple import from URL with default settings
 *
 * This is a convenience function that imports a recipe from a URL
 * using default settings and returns the Cooklang-formatted result.
 *
 * # Arguments
 * * `url` - The URL of the recipe webpage
 *
 * # Returns
 * A string containing the recipe in Cooklang format
 */
public func simpleImport(url: String) throws -> String {
    return try FfiConverterString.lift(rustCallWithError(FfiConverterTypeFfiImportError.lift) {
        uniffi_cooklang_import_fn_func_simple_import(
            FfiConverterString.lower(url), $0
        )
    })
}

private enum InitializationResult {
    case ok
    case contractVersionMismatch
    case apiChecksumMismatch
}

/// Use a global variable to perform the versioning checks. Swift ensures that
/// the code inside is only computed once.
private var initializationResult: InitializationResult = {
    // Get the bindings contract version from our ComponentInterface
    let bindings_contract_version = 26
    // Get the scaffolding contract version by calling the into the dylib
    let scaffolding_contract_version = ffi_cooklang_import_uniffi_contract_version()
    if bindings_contract_version != scaffolding_contract_version {
        return InitializationResult.contractVersionMismatch
    }
    if uniffi_cooklang_import_checksum_func_convert_image_to_cooklang() != 6900 {
        return InitializationResult.apiChecksumMismatch
    }
    if uniffi_cooklang_import_checksum_func_convert_text_to_cooklang() != 2319 {
        return InitializationResult.apiChecksumMismatch
    }
    if uniffi_cooklang_import_checksum_func_extract_recipe_from_url() != 45075 {
        return InitializationResult.apiChecksumMismatch
    }
    if uniffi_cooklang_import_checksum_func_get_version() != 33295 {
        return InitializationResult.apiChecksumMismatch
    }
    if uniffi_cooklang_import_checksum_func_import_from_url() != 49764 {
        return InitializationResult.apiChecksumMismatch
    }
    if uniffi_cooklang_import_checksum_func_is_provider_available() != 42076 {
        return InitializationResult.apiChecksumMismatch
    }
    if uniffi_cooklang_import_checksum_func_simple_import() != 32561 {
        return InitializationResult.apiChecksumMismatch
    }

    return InitializationResult.ok
}()

private func uniffiEnsureInitialized() {
    switch initializationResult {
    case .ok:
        break
    case .contractVersionMismatch:
        fatalError("UniFFI contract version mismatch: try cleaning and rebuilding your project")
    case .apiChecksumMismatch:
        fatalError("UniFFI API checksum mismatch: try cleaning and rebuilding your project")
    }
}

// swiftlint:enable all