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("ORDER_PROVIDER_TEST_ABORT"){var value=result("PROVIDER_FAILED");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)
  }}
 }}
final class FaultGate:@unchecked Sendable{
 var active=false;let mode=ProcessInfo.processInfo.environment["ORDER_FAULT_MODE"] ?? "",folder=ProcessInfo.processInfo.environment["ORDER_FAULT_BARRIER"] ?? ".";var events:[[String:Any]]=[]
 func event(_ event:String,_ detail:String=""){if active{let row:[String:Any]=["event":event,"detail":detail];events.append(row);print("ORDER_FAULT_EVENT "+String(decoding:try! JSONSerialization.data(withJSONObject:row),as:UTF8.self))}}
 func publish(_ name:String,_ value:[String:Any])throws{let temp=folder+"/"+name+".tmp";try JSONSerialization.data(withJSONObject:value).write(to:URL(fileURLWithPath:temp));guard rename(temp,folder+"/"+name+".json")==0 else{throw Denied.code("READY_RENAME_FAILED")}}
 func wait(_ name:String)async throws{let end=Date().addingTimeInterval(45);while !FileManager.default.fileExists(atPath:folder+"/"+name){guard Date()<end else{throw Denied.code("FAULT_BARRIER_TIMEOUT")};try await Task.sleep(nanoseconds:10_000_000)}}
 func gate(_ point:String)async throws{if !active || point=="after-inventory" && !["cancel","provider"].contains(mode) || point=="before-commit" && !["commit","control"].contains(mode){return};event("WAIT",point);try publish("ready",["pid":ProcessInfo.processInfo.processIdentifier,"mode":mode,"point":point]);if mode=="cancel"{try await wait("cancel");withUnsafeCurrentTask{$0?.cancel()};try Task.checkCancellation()}else{try await wait("release")}}
}
actor ObservedMutation:GraphTransactionExecutor{
 let inner:SQLiteDataService,g:FaultGate
 init(_ inner:SQLiteDataService,_ g:FaultGate){self.inner=inner;self.g=g}
 func execute(_ request:MutationRequest)async throws->MutationResult{let result:MutationResult;do{result=try await inner.execute(request)}catch{g.event("STATEMENT_ERROR",String(describing:error));throw error};if g.active,let metadata=result.metadata{print("ORDER_FAULT_NATIVE_SQL "+metadata.parameterizedSQL);print("ORDER_FAULT_NATIVE_AUDIT "+(metadata.auditReason ?? ""))};if request.mutation.kind == .update && request.mutation.entity.table=="inventory_data"{try await g.gate("after-inventory")};return result}
 func beginGraphTransaction()async throws{try await inner.beginGraphTransaction();g.event("BEGIN_OK")}
 func commitGraphTransaction()async throws{try await g.gate("before-commit");g.event("COMMIT_START");do{try await inner.commitGraphTransaction();g.event("COMMIT_OK")}catch{g.event("COMMIT_ERROR",String(describing:error));throw error}}
 func rollbackGraphTransaction()async throws{g.event("ROLLBACK_START");do{try await inner.rollbackGraphTransaction();g.event("ROLLBACK_OK")}catch{g.event("ROLLBACK_ERROR",String(describing:error));throw error}}
}
func faultRun(_ context:UserContext,_ provider:ObservedMutation,_ gate:FaultGate)async throws{
 let originalProvider=ObjectIdentifier(provider),originalRuntime="retained-value-context",request:[String:Any]=["requestKey":"REQ-FAULT","orderNumber":"ORD-STOCK-001","sku":"SKU-WIDGET","quantity":4];gate.active=true;print("ORDER_FAULT_BEGIN")
 let mode=gate.mode;let operation=Task{[context,mode] in if mode=="pre-cancel"{withUnsafeCurrentTask{$0?.cancel()};try Task.checkCancellation()};let localRequest:[String:Any]=["requestKey":"REQ-FAULT","orderNumber":"ORD-STOCK-001","sku":"SKU-WIDGET","quantity":4];let result=try await handle(context,"a",localRequest);return try JSONSerialization.data(withJSONObject:result)};var first:[String:Any]
 do{let data=try await operation.value,result=try JSONSerialization.jsonObject(with:data) as! [String:Any];first=["code":result["code"]!,"result":result]}catch{first=["code":error is CancellationError ? "CANCELLED":gate.mode=="commit" ? "COMMIT_FAILED":"UNEXPECTED_ERROR","type":String(describing:type(of:error)),"error":String(describing:error)]}
 first["pid"]=ProcessInfo.processInfo.processIdentifier;first["providerIdentity"]=String(describing:originalProvider);first["contextIdentity"]=String(describing:originalRuntime);first["events"]=gate.events;try gate.publish("failed",first);gate.active=false;try await gate.wait("recovery");print("ORDER_FAULT_RECOVERY");let recovery=try await handle(context,"a",request);let report:[String:Any]=["mode":gate.mode,"first":first,"recovery":recovery,"sameProvider":ObjectIdentifier(provider)==originalProvider,"sameContext":ObjectIdentifier(context.mutationExecutor as! ObservedMutation)==originalProvider,"tasksJoined":true];print("ORDER_FAULT_RESULT "+String(decoding:try JSONSerialization.data(withJSONObject:report,options:.sortedKeys),as:UTF8.self))
}
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 gate=FaultGate(),observed=ObservedMutation(provider,gate)
let context=UserContext(runtime:runtime,actor:"fault-server",trustedTenant:"server-scope",queryExecutor:provider,mutationExecutor:phase=="fault" ? observed:provider,requestPolicy:RequestPolicy{$0})
if ["bootstrap","seed"].contains(phase){try await context.ensureSchema(GeneratedRuntimeModule.module)};if phase=="seed"{try await seed(context)}else if phase=="fault"{try await faultRun(context,observed,gate)}else if phase != "bootstrap"{throw Denied.code("INVALID_PHASE")};print("ORDER_OK phase="+phase)
