"""Synthetic scope acceptance only; no network, shop, account or API access.

Run: python3 subscription_scope_check.py --test
     python3 subscription_scope_check.py subscription-scope-fixtures.json
All fields are supplied declarations, not independently authenticated evidence.
"""
import json
import sys
import unittest
from pathlib import Path

def check(p):
    if p.get('plan') not in ('pay-per-delivery','prepaid') or not p.get('appVersion'):
        return 'HOLD_PLAN_OR_APP_IDENTITY'
    if p.get('plan')=='prepaid' and p.get('operation')=='line-quantity':
        return 'HOLD_PREPAID_QUANTITY_PATH'
    if not p.get('expectedOrderId') or not p.get('expectedContractId'):
        return 'HOLD_EXPECTED_OBJECTS'
    order,contract=p.get('order',{}),p.get('contract',{})
    if order.get('id')!=p['expectedOrderId'] or contract.get('id')!=p['expectedContractId']:
        return 'HOLD_OBJECT_IDENTITY'
    scope=p.get('scope')
    if scope=='cancel-contract':
        return 'DECLARED_CONTRACT_CANCELLED_ONLY' if contract.get('cancelled') is True else 'HOLD_CONTRACT_CANCELLATION'
    if scope=='prepaid-address':
        if not order.get('address') or not contract.get('address'): return 'HOLD_ADDRESS_RECORD'
        return 'DECLARED_ADDRESSES_MATCH_ONLY' if order['address']==contract['address'] else 'HOLD_OBJECT_SYNC'
    q=p.get('desiredQuantity')
    if type(q) is not int or q<1: return 'HOLD_QUANTITY_INPUT'
    if scope=='one-delivery':
        if order.get('quantity')!=q: return 'HOLD_CURRENT_DELIVERY'
        before=p.get('contractBeforeQuantity')
        if type(before) is not int or contract.get('quantity')!=before: return 'HOLD_UNINTENDED_CONTRACT_CHANGE'
        return 'DECLARED_ONE_DELIVERY_ONLY'
    if scope=='all-future':
        preview=p.get('nextCyclePreview',{})
        if not contract.get('revision') or preview.get('contractId')!=p['expectedContractId']:
            return 'HOLD_FUTURE_EVIDENCE'
        if contract.get('quantity')!=q or preview.get('quantity')!=q: return 'HOLD_FUTURE_QUANTITY'
        return 'DECLARED_FUTURE_PACKET_MATCHES_ONLY'
    return 'HOLD_SCOPE'

def base():
    return {'plan':'pay-per-delivery','appVersion':'TeachingApp/v1','expectedOrderId':'O17','expectedContractId':'C17','scope':'one-delivery','desiredQuantity':2,'contractBeforeQuantity':1,'order':{'id':'O17','quantity':2},'contract':{'id':'C17','quantity':1}}

class Tests(unittest.TestCase):
    def test_failure_and_success_boundaries(self):
        b=base()
        cases=[
            (b,'DECLARED_ONE_DELIVERY_ONLY'),
            ({**b,'appVersion':None},'HOLD_PLAN_OR_APP_IDENTITY'),
            ({**b,'expectedOrderId':None},'HOLD_EXPECTED_OBJECTS'),
            ({**b,'order':{'id':'OTHER','quantity':2}},'HOLD_OBJECT_IDENTITY'),
            ({**b,'order':{'id':'O17','quantity':1}},'HOLD_CURRENT_DELIVERY'),
            ({**b,'contract':{'id':'C17','quantity':2}},'HOLD_UNINTENDED_CONTRACT_CHANGE'),
            ({**b,'desiredQuantity':True},'HOLD_QUANTITY_INPUT'),
            ({**b,'scope':'all-future'},'HOLD_FUTURE_EVIDENCE'),
            ({**b,'scope':'all-future','contract':{'id':'C17','revision':'r2','quantity':2},'nextCyclePreview':{'contractId':'C17','quantity':1}},'HOLD_FUTURE_QUANTITY'),
            ({**b,'scope':'all-future','contract':{'id':'C17','revision':'r2','quantity':2},'nextCyclePreview':{'contractId':'C17','quantity':2}},'DECLARED_FUTURE_PACKET_MATCHES_ONLY'),
            ({**b,'plan':'prepaid','operation':'line-quantity'},'HOLD_PREPAID_QUANTITY_PATH'),
            ({**b,'plan':'prepaid','scope':'prepaid-address','order':{'id':'O17','address':'A'},'contract':{'id':'C17','address':'B'}},'HOLD_OBJECT_SYNC'),
            ({**b,'scope':'cancel-contract','order':{'id':'O17','cancelled':True}},'HOLD_CONTRACT_CANCELLATION'),
            ({**b,'scope':'cancel-contract','contract':{'id':'C17','cancelled':True}},'DECLARED_CONTRACT_CANCELLED_ONLY')
        ]
        for packet,expected in cases:
            with self.subTest(expected=expected): self.assertEqual(check(packet),expected)

if __name__=='__main__':
    if len(sys.argv)!=2: raise SystemExit('Supply --test or the filled fixture JSON path')
    if sys.argv[1]=='--test': unittest.main(argv=[sys.argv[0]])
    else:
        data=json.loads(Path(sys.argv[1]).read_text())
        rows=[{'case':r['case'],'expected':r['expected'],'actual':check(r['input'])} for r in data['cases']]
        print(json.dumps({'synthetic':True,'liveTest':False,'allExpectedMatched':all(r['actual']==r['expected'] for r in rows),'rows':rows},indent=2))
