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 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 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 stressReason="Stress Order and item atomically"
final class LifeProbe:@unchecked Sendable{weak var provider:SQLiteDataService?}
final class Gate:@unchecked Sendable{
 var mode="normal",calibrate=false;var transactions=0,tasks=0,started=0,finished=0;let folder=ProcessInfo.processInfo.environment["ORDER_STRESS_FOLDER"] ?? "."
 func fd()->Int{(try? FileManager.default.contentsOfDirectory(atPath:"/dev/fd").count) ?? -1}
 func metrics()->[String:Any]{["activeTransactions":transactions,"activeTasks":tasks,"startedTasks":started,"finishedTasks":finished,"fd":fd()]}
 func publish(_ name:String,_ value:[String:Any])throws{let tmp=folder+"/"+name+".tmp";try JSONSerialization.data(withJSONObject:value).write(to:URL(fileURLWithPath:tmp));guard rename(tmp,folder+"/"+name+".json")==0 else{throw Denied.code("RENAME_FAILED")}}
 func wait(_ name:String)async throws{let end=Date().addingTimeInterval(90);while !FileManager.default.fileExists(atPath:folder+"/"+name){guard Date()<end else{throw Denied.code("STRESS_PROTOCOL_TIMEOUT "+name)};try await Task.sleep(nanoseconds:2_000_000)}}
 func checkpoint()async throws{if mode=="cancel"{if calibrate{try publish("held",metrics());try await wait("held-release")};withUnsafeCurrentTask{$0?.cancel()};try Task.checkCancellation()}}
}
actor ObservedMutation:GraphTransactionExecutor{
 let inner:SQLiteDataService,g:Gate
 init(_ inner:SQLiteDataService,_ g:Gate){self.inner=inner;self.g=g}
 func execute(_ request:MutationRequest)async throws->MutationResult{let result=try await inner.execute(request);if let m=result.metadata{print("ORDER_STRESS_SQL "+m.parameterizedSQL+" AUDIT "+(m.auditReason ?? ""))};if request.mutation.kind == .update && request.mutation.entity.table=="customer_order_data"{try await g.checkpoint()};return result}
 func beginGraphTransaction()async throws{try await inner.beginGraphTransaction();g.transactions+=1}
 func commitGraphTransaction()async throws{try await inner.commitGraphTransaction();g.transactions-=1}
 func rollbackGraphTransaction()async throws{try await inner.rollbackGraphTransaction();g.transactions-=1}
}
func edit(_ context:UserContext,_ g:Gate,_ data:Data)async throws->Data{
 let r=try JSONSerialization.jsonObject(with:data) as! [String:Any]
 let roots=try await Q.commercePlatforms().withTenantKeyIs("TENANT-A").limit(2).comment("Resolve trusted stress tenant").purpose(stressReason).executeForList(context);guard roots.count==1 else{throw Denied.code("INVALID_ROOT")};let rid=try required(E.commercePlatform(roots[0]).id().eval())
 let orders=try await Q.customerOrders().filterByCommercePlatform(rid).withBuyerReferenceIs(r["buyer"] as! String).withOrderNumberIs(r["orderNumber"] as! String).selectOrderItemListWith(Q.orderItems().limit(2)).limit(2).comment("Load complete bounded Order and item").purpose(stressReason).executeForList(context);guard orders.count==1 else{throw Denied.code("INVALID_ORDER")};var o=orders[0];guard o.orderItemList.count==1 else{throw Denied.code("INVALID_ITEM")}
 var result:[String:Any]=["originalOrderVersion":try required(E.customerOrder(o).version().eval()),"originalItemVersion":try required(E.orderItem(o.orderItemList[0]).version().eval())];if r["cohort"] as? Bool == true{try g.publish("preloaded",result);try await g.wait("cohort-release")}
 o.updateOrderNote(r["token"] as? String);o.orderItemList[0].updateProductName(r["token"] as? String)
 do{_ = try await o.auditAs(stressReason).save(context);result["outcome"]="COMMITTED"}catch{let text=String(describing:error);result["outcome"]=error is CancellationError ? "CANCELLED":text.contains("ORDER_STRESS_PROVIDER_ABORT") ? "PROVIDER_FAILED":conflict(error) ? "CONFLICT":"ERROR";result["error"]=text;result["type"]=String(describing:type(of:error))};return try JSONSerialization.data(withJSONObject:result)
}
func ownedWorker(_ life:LifeProbe,_ g:Gate)async throws->Int{
 let provider=try SQLiteDataService(path:required(ProcessInfo.processInfo.environment["ORDER_DATABASE"]));life.provider=provider;var runtime=TeaQLRuntime();try runtime.install(GeneratedRuntimeModule.module);let observed=ObservedMutation(provider,g),context=UserContext(runtime:runtime,actor:"stress-server",trustedTenant:"TENANT-A",queryExecutor:provider,mutationExecutor:observed,requestPolicy:RequestPolicy{$0})
 try g.publish("ready",["pid":ProcessInfo.processInfo.processIdentifier,"providerIdentity":String(describing:ObjectIdentifier(provider))]);var n=0
 while true{try await g.wait(String(n)+".command.json");let data=try Data(contentsOf:URL(fileURLWithPath:g.folder+"/"+String(n)+".command.json")),r=try JSONSerialization.jsonObject(with:data) as! [String:Any];if r["action"] as? String == "close"{return n};var result:[String:Any]=[:];if r["action"] as? String == "edit"{g.mode=r["mode"] as! String;g.calibrate=r["calibrate"] as? Bool ?? false;g.tasks+=1;g.started+=1;let task=Task{try await edit(context,g,data)};let output=try await task.value;result=try JSONSerialization.jsonObject(with:output) as! [String:Any];g.tasks-=1;g.finished+=1};result["metrics"]=g.metrics();result["pid"]=ProcessInfo.processInfo.processIdentifier;result["closed"]=false;try g.publish(String(n)+".result",result);n+=1}
}
func main()async throws{let phase=try required(CommandLine.arguments.dropFirst().first)
 if phase=="stress"{let life=LifeProbe(),g=Gate(),n=try await ownedWorker(life,g);let end=Date().addingTimeInterval(5);while life.provider != nil && Date()<end{try await Task.sleep(nanoseconds:1_000_000)};guard life.provider == nil else{throw Denied.code("PROVIDER_NOT_RELEASED")};var metrics=g.metrics();metrics["providerReleased"]=true;metrics["openConnections"]=0;try g.publish(String(n)+".result",["metrics":metrics,"pid":ProcessInfo.processInfo.processIdentifier,"closed":true])}
 else{let provider=try SQLiteDataService(path:required(ProcessInfo.processInfo.environment["ORDER_DATABASE"]));var runtime=TeaQLRuntime();try runtime.install(GeneratedRuntimeModule.module);let context=UserContext(runtime:runtime,queryExecutor:provider,mutationExecutor:provider,requestPolicy:RequestPolicy{$0});try await context.ensureSchema(GeneratedRuntimeModule.module);if phase=="seed"{try await seed(context)}else if phase != "bootstrap"{throw Denied.code("INVALID_PHASE")}}
 print("ORDER_OK phase="+phase)
}
try await main()
