"""Server-owned stock facade. All writes use generated audited graph mutations."""
import asyncio,json,os,re,sys,time
from pathlib import Path
from Q import Q
from E import E
from runtime_module import GENERATED_RUNTIME_MODULE
from teaql.provider.sqlite import create_sqlite_service
from teaql.runtime import UserContext
SEED='Seed stock reservation fixture';RESERVE='Reserve Order inventory atomically'
TRUSTED={'a':('ACTOR-A','TENANT-A','BUYER-A'),'b':('ACTOR-B','TENANT-A','BUYER-B'),'c':('ACTOR-C','TENANT-B','BUYER-A')}
class Denied(Exception):pass

def validate(token,r):
    if token not in TRUSTED:raise Denied('UNAUTHENTICATED')
    if any(k in r for k in ['tenant','buyer','actor','permissions','policy','userContext']):raise Denied('FORGED_SCOPE')
    if set(r)!={'requestKey','orderNumber','sku','quantity'}:raise Denied('INVALID_REQUEST')
    if type(r['quantity']) is not int or not 1<=r['quantity']<=10:raise Denied('INVALID_REQUEST')
    if not isinstance(r['requestKey'],str) or re.fullmatch('[A-Z0-9-]{1,64}',r['requestKey']) is None:raise Denied('INVALID_REQUEST')
    if any(not isinstance(r[k],str) or not 1<=len(r[k])<=64 for k in ['orderNumber','sku']):raise Denied('INVALID_REQUEST')

def conflict(error):
    t=str(error).lower()
    return not any(w in t for w in ['busy','locked','timeout']) and any(w in t for w in ['version','optimistic','conflict','stale','authoritative persisted state'])

async def barrier(root,order,inventory,r,token):
    if not os.environ.get('ORDER_BARRIER'):return
    folder=Path(os.environ['ORDER_BARRIER']);worker=os.environ['ORDER_WORKER']
    ready={'pid':os.getpid(),'session':token,'requestKey':r['requestKey'],'orderNumber':r['orderNumber'],'quantity':r['quantity'],'rootVersion':E.commerce_platform(root).version().eval(),'inventoryVersion':E.inventory(inventory).version().eval(),'available':E.inventory(inventory).available_quantity().eval(),'orderVersion':E.customer_order(order).version().eval()}
    temporary=folder/(worker+'.tmp');temporary.write_text(json.dumps(ready));temporary.replace(folder/(worker+'.ready'))
    deadline=time.monotonic()+45
    while not (folder/'release').exists():
        if time.monotonic()>deadline:raise RuntimeError('Barrier timeout')
        await asyncio.sleep(.01)

async def handle(context,token,r):
    reasons=[];attempts=0
    def result(code,receipt=None):return {'code':code,'receiptId':receipt,'attempts':attempts,'conflicts':len(reasons),'conflictReasons':reasons}
    try:
        validate(token,r);actor,tenant,buyer=TRUSTED[token]
        for attempt in range(3):
            attempts+=1
            roots=await (Q.commerce_platforms().with_tenant_key_is(tenant)
                .select_customer_order_list_with(Q.customer_orders().with_buyer_reference_is(buyer).with_order_number_is(r['orderNumber']).limit(2))
                .select_inventory_list_with(Q.inventory().with_sku_code_is(r['sku']).limit(2))
                .select_stock_reservation_list_with(Q.stock_reservations().with_buyer_reference_is(buyer).with_request_key_is(r['requestKey']).limit(2))
                .limit(2).comment('Load trusted tenant reservation aggregate').purpose('Bind Order inventory and receipt to server session').execute_for_list(context))
            if len(roots)!=1:raise RuntimeError('Invalid trusted root')
            root=roots[0];receipts=root.stock_reservation_list()
            if len(receipts)>1:raise RuntimeError('Duplicate persisted request key')
            if receipts:
                e=E.stock_reservation(receipts[0]);same=e.order_number().eval()==r['orderNumber'] and e.sku_code().eval()==r['sku'] and e.quantity().eval()==r['quantity']
                return result('REPLAY' if same else 'IDEMPOTENCY_CONFLICT',e.id().eval() if same else None)
            orders=root.customer_order_list();stocks=root.inventory_list()
            if len(orders)!=1 or len(stocks)!=1:raise Denied('NOT_FOUND')
            order,stock=orders[0],stocks[0];oe=E.customer_order(order);se=E.inventory(stock)
            if oe.order_status_id().eval()!=1001:raise Denied('ORDER_NOT_DRAFT')
            items=await (Q.order_items().filter_by_customer_order(oe.id().eval()).limit(2).comment('Validate complete bounded Order items').purpose('Reject mismatched reservation quantity or SKU').execute_for_list(context))
            if len(items)!=1 or E.order_item(items[0]).sku_code().eval()!=r['sku'] or E.order_item(items[0]).quantity().eval()!=r['quantity']:raise Denied('INVALID_ORDER_ITEMS')
            available,reserved=se.available_quantity().eval(),se.reserved_quantity().eval()
            if available<0 or reserved<0:raise RuntimeError('Invalid inventory')
            if available<r['quantity']:raise Denied('OUT_OF_STOCK')
            if attempt==0:await barrier(root,order,stock,r,token)
            root.update_reservation_sequence(E.commerce_platform(root).reservation_sequence().eval()+1);order.update_order_status(1002);stock.update_available_quantity(available-r['quantity']);stock.update_reserved_quantity(reserved+r['quantity'])
            receipt=Q.stock_reservations().comment('Create immutable scoped reservation receipt').purpose('Commit request idempotency with inventory').new_entity(context)
            receipt.update_commerce_platform(root);receipt.update_customer_order(order);receipt.update_inventory(stock);receipt.update_request_key(r['requestKey']);receipt.update_buyer_reference(buyer);receipt.update_quantity(r['quantity']);receipt.update_order_number(r['orderNumber']);receipt.update_sku_code(r['sku']);receipts.append(receipt)
            try:await root.audit_as(RESERVE).save(context)
            except Exception as error:
                if 'STOCK_RESERVATION_TEST_ABORT' in str(error):return {**result('TRANSACTION_ABORTED'),'reason':str(error)}
                if not conflict(error):raise
                reasons.append(str(error));continue
            saved=await (Q.stock_reservations().filter_by_commerce_platform(E.commerce_platform(root).id().eval()).with_buyer_reference_is(buyer).with_request_key_is(r['requestKey']).limit(2).comment('Read committed reservation receipt').purpose('Return durable idempotency identity').execute_for_list(context))
            assert len(saved)==1
            return result('RESERVED',E.stock_reservation(saved[0]).id().eval())
        return result('CONFLICT_LIMIT')
    except Denied as e:return result(str(e))

async def seed(context):
    fixture=json.load(open(os.environ['ORDER_FIXTURE']));roots=await Q.commerce_platforms().limit(2).comment('Read initialized stock root').purpose(SEED).execute_for_list(context);assert len(roots)==1
    for n,t in enumerate(fixture['tenants']):
        root=roots[0] if n==0 else Q.commerce_platforms().comment('Create tenant').purpose(SEED).new_entity(context)
        root.update_name('Tenant '+t['key'][-1]);root.update_tenant_key(t['key']);root.update_reservation_sequence(0);await root.audit_as(SEED).save(context)
        for sku,qty in [(fixture['sku'],t['available']),(fixture['controlSku'],fixture['controlAvailable'])]:
            stock=Q.inventory().comment('Create SKU inventory').purpose(SEED).new_entity(context);stock.update_commerce_platform(root);stock.update_sku_code(sku);stock.update_available_quantity(qty);stock.update_reserved_quantity(0);stock.update_warehouse_note('Initial warehouse stock');await stock.audit_as(SEED).save(context)
        for buyer in fixture['buyers']:
            for d in fixture['orders']:
                o=Q.customer_orders().comment('Create stock Order').purpose(SEED).new_entity(context);o.update_commerce_platform(root);o.update_order_status_to_draft();o.update_order_number(d['number']);o.update_buyer_reference(buyer);o.update_currency_code('USD');o.update_total_minor(d['quantity']*fixture['unitPriceMinor']);o.update_order_note('Stock reservation fixture order');await o.audit_as(SEED).save(context)
                i=Q.order_items().comment('Create complete Order line').purpose(SEED).new_entity(context);i.update_customer_order(o);i.update_sku_code(fixture['sku']);i.update_product_name(fixture['sku']);i.update_quantity(d['quantity']);i.update_unit_price_minor(fixture['unitPriceMinor']);i.update_line_total_minor(d['quantity']*fixture['unitPriceMinor']);await i.audit_as(SEED).save(context)
async def main():
    context=UserContext.new().install(GENERATED_RUNTIME_MODULE);context.insert_resource('dataService',create_sqlite_service(os.environ['ORDER_DATABASE']));phase=sys.argv[1]
    if phase in ['bootstrap','seed']:await context.ensure_schema()
    if phase=='seed':await seed(context)
    elif phase in ['request','worker']:
        print('ORDER_STOCK_BEGIN',flush=True);print('ORDER_STOCK_RESULT '+json.dumps(await handle(context,os.environ.get('ORDER_SESSION',''),json.load(open(os.environ['ORDER_REQUEST'])))))
    elif phase!='bootstrap':raise RuntimeError('Unknown phase')
    print('ORDER_OK phase='+phase)
if __name__=='__main__':asyncio.run(main())
