import Foundation
import CoreFoundation
import Darwin
import TeaQLCore
import TeaQLSQLite
import GeneratedTeaQL
let seedReason="Seed stock reservation fixture",reserveReason="Reserve Order inventory atomically"
enum Denied:Error{case code(String)}
let trusted:[String:[String]]=["a":["ACTOR-A","TENANT-A","BUYER-A"],"b":["ACTOR-B","TENANT-A","BUYER-B"],"c":["ACTOR-C","TENANT-B","BUYER-A"]]
func required<T>(_ v:T?)throws->T{guard let v else{throw Denied.code("MISSING_LOADED_VALUE")};return v}
func integer(_ v:Any?)->Int64?{guard let n=v as? NSNumber,CFGetTypeID(n) != CFBooleanGetTypeID(),n.doubleValue.isFinite,n.doubleValue.rounded(.towardZero)==n.doubleValue else{return nil};return n.int64Value}
func validate(_ token:String,_ r:[String:Any])throws{guard trusted[token] != nil else{throw Denied.code("UNAUTHENTICATED")};if ["tenant","buyer","actor","permissions","policy","userContext"].contains(where:{r[$0] != nil}){throw Denied.code("FORGED_SCOPE")};guard Set(r.keys)==Set(["requestKey","orderNumber","sku","quantity"]),let q=integer(r["quantity"]),(1...10).contains(q),let key=r["requestKey"] as? String,key.range(of:"\\A[A-Z0-9-]{1,64}\\z",options:.regularExpression) != nil else{throw Denied.code("INVALID_REQUEST")};for k in ["orderNumber","sku"]{guard let s=r[k] as? String,(1...64).contains(s.count) else{throw Denied.code("INVALID_REQUEST")}}}
func conflict(_ error:Error)->Bool{let t=String(describing:error).lowercased();return !["busy","locked","timeout"].contains(where:t.contains)&&["version","optimistic","conflict","stale","authoritative persisted state"].contains(where:t.contains)}
func barrier(_ ready:[String:Any])async throws{let env=ProcessInfo.processInfo.environment;guard let folder=env["ORDER_BARRIER"] else{return};let worker=env["ORDER_WORKER"]!,temp=folder+"/"+worker+".tmp";try JSONSerialization.data(withJSONObject:ready).write(to:URL(fileURLWithPath:temp));guard rename(temp,folder+"/"+worker+".ready")==0 else{throw Denied.code("READY_RENAME_FAILED")};let end=Date().addingTimeInterval(45);while !FileManager.default.fileExists(atPath:folder+"/release"){guard Date()<end else{throw Denied.code("BARRIER_TIMEOUT")};try await Task.sleep(nanoseconds:10_000_000)}}
func handle(_ context:UserContext,_ token:String,_ r:[String:Any])async throws->[String:Any]{var attempts=0,reasons:[String]=[];func result(_ code:String,_ id:Int64?=nil)->[String:Any]{["code":code,"receiptId":id as Any? ?? NSNull(),"attempts":attempts,"conflicts":reasons.count,"conflictReasons":reasons]};do{
 try validate(token,r);let s=trusted[token]!,tenant=s[1],buyer=s[2],key=r["requestKey"] as! String,number=r["orderNumber"] as! String,sku=r["sku"] as! String,qty=integer(r["quantity"])!
 for attempt in 0..<3{
  attempts+=1;let roots=try await Q.commercePlatforms().withTenantKeyIs(tenant)
   .selectCustomerOrderListWith(Q.customerOrders().withBuyerReferenceIs(buyer).withOrderNumberIs(number).limit(2))
   .selectInventoryListWith(Q.inventory().withSkuCodeIs(sku).limit(2))
   .selectStockReservationListWith(Q.stockReservations().withBuyerReferenceIs(buyer).withRequestKeyIs(key).limit(2))
   .limit(2).comment("Load trusted tenant reservation aggregate").purpose("Bind Order inventory and receipt to server session").executeForList(context)
  guard roots.count==1 else{throw Denied.code("INVALID_TRUSTED_SCOPE")};var root=roots[0];guard root.stockReservationList.count<=1 else{throw Denied.code("DUPLICATE_PERSISTED_KEY")}
  if let receipt=root.stockReservationList.first{let e=E.stockReservation(receipt);let same=try e.orderNumber().eval()==number && e.skuCode().eval()==sku && e.quantity().eval()==qty;return result(same ? "REPLAY":"IDEMPOTENCY_CONFLICT",same ? try required(e.id().eval()):nil)}
  guard root.customerOrderList.count==1,root.inventoryList.count==1 else{throw Denied.code("NOT_FOUND")};let order=root.customerOrderList[0],stock=root.inventoryList[0],oe=E.customerOrder(order),se=E.inventory(stock),rid=try required(E.commercePlatform(root).id().eval()),oid=try required(oe.id().eval()),iid=try required(se.id().eval())
  guard try oe.orderStatusId().eval()==1001 else{throw Denied.code("ORDER_NOT_DRAFT")};let items=try await Q.orderItems().filterByCustomerOrder(oid).limit(2).comment("Validate complete bounded Order items").purpose("Reject mismatched reservation quantity or SKU").executeForList(context)
  guard items.count==1,try E.orderItem(items[0]).skuCode().eval()==sku,try E.orderItem(items[0]).quantity().eval()==qty else{throw Denied.code("INVALID_ORDER_ITEMS")};let available=try required(se.availableQuantity().eval()),reserved=try required(se.reservedQuantity().eval());guard available>=0,reserved>=0 else{throw Denied.code("INVALID_INVENTORY")};guard available>=qty else{throw Denied.code("OUT_OF_STOCK")}
  if attempt==0{try await barrier(["pid":ProcessInfo.processInfo.processIdentifier,"session":token,"requestKey":key,"orderNumber":number,"quantity":qty,"rootVersion":try required(E.commercePlatform(root).version().eval()),"inventoryVersion":try required(se.version().eval()),"available":available,"orderVersion":try required(oe.version().eval())])}
  root.updateReservationSequence(try required(E.commercePlatform(root).reservationSequence().eval())+1);root.customerOrderList[0].updateOrderStatus(1002);root.inventoryList[0].updateAvailableQuantity(available-qty);root.inventoryList[0].updateReservedQuantity(reserved+qty)
  var receipt=try Q.stockReservations().comment("Create immutable scoped reservation receipt").purpose("Commit request idempotency with inventory").newEntity(context);receipt.updateCommercePlatform(rid);receipt.updateCustomerOrder(oid);receipt.updateInventory(iid);receipt.updateRequestKey(key);receipt.updateBuyerReference(buyer);receipt.updateQuantity(qty);receipt.updateOrderNumber(number);receipt.updateSkuCode(sku);root.stockReservationList.append(receipt)
  do{_ = try await root.auditAs(reserveReason).save(context)}catch{let text=String(describing:error);if text.contains("STOCK_RESERVATION_TEST_ABORT"){var value=result("TRANSACTION_ABORTED");value["reason"]=text;return value};guard conflict(error) else{throw error};reasons.append(text);continue}
  let saved=try await Q.stockReservations().filterByCommercePlatform(rid).withBuyerReferenceIs(buyer).withRequestKeyIs(key).limit(2).comment("Read committed reservation receipt").purpose("Return durable idempotency identity").executeForList(context);guard saved.count==1 else{throw Denied.code("MISSING_RECEIPT")};return result("RESERVED",try required(E.stockReservation(saved[0]).id().eval()))
 };return result("CONFLICT_LIMIT")
 }catch Denied.code(let code){return result(code)}}
func seed(_ context:UserContext)async throws{let env=ProcessInfo.processInfo.environment,f=try JSONSerialization.jsonObject(with:Data(contentsOf:URL(fileURLWithPath:required(env["ORDER_FIXTURE"])))) as! [String:Any],roots=try await Q.commercePlatforms().limit(2).comment("Read initialized stock root").purpose(seedReason).executeForList(context);guard roots.count==1 else{throw Denied.code("INVALID_ROOT")}
 for (n,t) in (f["tenants"] as! [[String:Any]]).enumerated(){let tenant=t["key"] as! String;var root=n==0 ? roots[0]:try Q.commercePlatforms().comment("Create tenant").purpose(seedReason).newEntity(context);root.updateName("Tenant "+String(tenant.suffix(1)));root.updateTenantKey(tenant);root.updateReservationSequence(0);_ = try await root.auditAs(seedReason).save(context)
  let stored=try await Q.commercePlatforms().withTenantKeyIs(tenant).limit(2).comment("Reload tenant identity").purpose(seedReason).executeForList(context);guard stored.count==1 else{throw Denied.code("INVALID_ROOT")};let rid=try required(E.commercePlatform(stored[0]).id().eval())
  for k in 0..<2{var stock=try Q.inventory().comment("Create SKU inventory").purpose(seedReason).newEntity(context);stock.updateCommercePlatform(rid);stock.updateSkuCode(f[k==0 ? "sku":"controlSku"] as? String);stock.updateAvailableQuantity(integer(k==0 ? t["available"]:f["controlAvailable"])!);stock.updateReservedQuantity(0);stock.updateWarehouseNote("Initial warehouse stock");_ = try await stock.auditAs(seedReason).save(context)}
  for buyer in f["buyers"] as! [String]{for d in f["orders"] as! [[String:Any]]{let number=d["number"] as! String,qty=integer(d["quantity"])!,price=integer(f["unitPriceMinor"])!;var o=try Q.customerOrders().comment("Create stock Order").purpose(seedReason).newEntity(context);o.updateCommercePlatform(rid);o.updateOrderStatusToDraft();o.updateOrderNumber(number);o.updateBuyerReference(buyer);o.updateCurrencyCode("USD");o.updateTotalMinor(qty*price);o.updateOrderNote("Stock reservation fixture order");_ = try await o.auditAs(seedReason).save(context)
   let saved=try await Q.customerOrders().filterByCommercePlatform(rid).withBuyerReferenceIs(buyer).withOrderNumberIs(number).limit(2).comment("Reload saved Order identity").purpose(seedReason).executeForList(context);guard saved.count==1 else{throw Denied.code("INVALID_ORDER")};let oid=try required(E.customerOrder(saved[0]).id().eval());var i=try Q.orderItems().comment("Create complete Order line").purpose(seedReason).newEntity(context);i.updateCustomerOrder(oid);i.updateSkuCode(f["sku"] as? String);i.updateProductName(f["sku"] as? String);i.updateQuantity(qty);i.updateUnitPriceMinor(price);i.updateLineTotalMinor(qty*price);_ = try await i.auditAs(seedReason).save(context)
  }}
 }}
let phase=try required(CommandLine.arguments.dropFirst().first),env=ProcessInfo.processInfo.environment,provider=try SQLiteDataService(path:required(env["ORDER_DATABASE"]));var runtime=TeaQLRuntime();try runtime.install(GeneratedRuntimeModule.module);let context=UserContext(runtime:runtime,actor:"stock-server",trustedTenant:"server-scope",queryExecutor:provider,mutationExecutor:provider,requestPolicy:RequestPolicy{$0})
if ["bootstrap","seed"].contains(phase){try await context.ensureSchema(GeneratedRuntimeModule.module)};if phase=="seed"{try await seed(context)}else if ["request","worker"].contains(phase){print("ORDER_STOCK_BEGIN");let r=try JSONSerialization.jsonObject(with:Data(contentsOf:URL(fileURLWithPath:required(env["ORDER_REQUEST"])))) as! [String:Any],result=try await handle(context,env["ORDER_SESSION"] ?? "",r);print("ORDER_STOCK_RESULT "+String(decoding:try JSONSerialization.data(withJSONObject:result,options:.sortedKeys),as:UTF8.self))}else if phase != "bootstrap"{throw Denied.code("INVALID_PHASE")};print("ORDER_OK phase="+phase)
