import SwiftUI
import FoundationModels
import Vision
import UIKit

struct ContentView: View {
   @State private var barcode: String = "Reading..."
   @State private var codeType: String = ""

   var body: some View {
      VStack {
         Image(uiImage: UIImage(named: "magazineqr")!)
            .resizable()
            .scaledToFit()
            .padding()
         Text(barcode)
         Text(codeType)
         Spacer()
      }
      .padding()
      .task {
         let image = UIImage(named: "magazineqr")!
         let tool = BarcodeReaderTool()
         let session = LanguageModelSession(tools: [tool])

         do {
            let response = try await session.respond(generating: BarcodeData.self) {
               "Scan the image and return the content encoded in the barcode."
               Attachment(image)
                  .label("magazine-qr")
            }
            barcode = response.content.info
         } catch {
            print("Error performing the request: \(error)")
         }
      }
   }
}
@Generable
struct BarcodeData {
   @Guide(description: "Information in the barcode")
   let info: String
}