"""Fictitious V1 form preparation only. No Stripe client, HTTP request or billing operation."""
from collections import Counter
from copy import deepcopy
import hashlib
import importlib.metadata
import inspect
import json
from pathlib import Path
from urllib.parse import parse_qsl, urlencode

from stripe._encode import _api_encode

CHECKS = 0
NATIVE_CALLS = 0
OBSERVATIONS = []
SUB = 'sub_DEMO_50'
CORE = 'si_DEMO_CORE_50'
ADDON = 'si_DEMO_ADDON_50'
NEW_PRICE = 'price_DEMO_NEW_50'
ERP_LINE = 'LICENCE-CORE-FICT'


def check(condition, label):
    global CHECKS
    if not condition:
        raise AssertionError(label)
    CHECKS += 1


check(importlib.metadata.version('stripe') == '16.0.0', 'Pinned Stripe distribution')
source = Path(inspect.getsourcefile(_api_encode))
check(hashlib.sha256(source.read_bytes()).hexdigest() ==
      '474b2d5fc40de975f62f95fae02c169c8fcb742087a5f30bc18e9ad84c3dd57b',
      'Original released encoder source')


def complete_item(**changes):
    item = {'id': CORE, 'price': NEW_PRICE, 'quantity': 7}
    item.update(changes)
    return item


def local_decision(params, fields):
    # This is our explicit preserve-seven-units profile, not Stripe server validation.
    repeated = [key for key, count in Counter(key for key, _ in fields).items() if count > 1]
    if repeated:
        return 'duplicate_form_key_review'
    items = params.get('items')
    if not isinstance(items, list) or len(items) != 1 or not isinstance(items[0], dict):
        return 'requested_line_count_review'
    item = items[0]
    if item.get('id') != CORE:
        return 'existing_item_identity_review'
    if item.get('price') != NEW_PRICE:
        return 'price_intent_review'
    if item.get('quantity') is None:
        return 'preserved_quantity_review'
    if type(item['quantity']) is not int:
        return 'quantity_type_review'
    if item['quantity'] != 7:
        return 'quantity_change_review'
    wire = dict(fields)
    if (wire.get('items[0][id]'), wire.get('items[0][price]'), wire.get('items[0][quantity]')) != (CORE, NEW_PRICE, '7'):
        return 'wire_intent_review'
    return 'ready_prepared_existing_item'


def choose_current_item(snapshot, bindings):
    candidates = [binding for binding in bindings if binding['erpLine'] == ERP_LINE]
    if not candidates:
        return None, 'binding_missing_review'
    if len(candidates) != 1:
        return None, 'binding_ambiguous_review'
    binding = candidates[0]
    if snapshot['id'] != binding['subscriptionId']:
        return None, 'subscription_identity_review'
    if snapshot['items']['has_more']:
        return None, 'selection_incomplete_review'
    rows = [item for item in snapshot['items']['data'] if item['id'] == binding['itemId']]
    if len(rows) != 1:
        return None, 'current_item_identity_review'
    return rows[0], None


binding = {'erpLine': ERP_LINE, 'subscriptionId': SUB, 'itemId': CORE}
snapshot = {'id': SUB, 'items': {'has_more': False, 'data': [
    {'id': ADDON, 'price': {'id': 'price_DEMO_ADDON_50'}, 'quantity': 1},
    {'id': CORE, 'price': {'id': 'price_DEMO_OLD_50'}, 'quantity': 7},
]}}
selected, reason = choose_current_item(snapshot, [binding])
check(reason is None and selected['id'] == CORE, 'Approved mapping selects core after reordering')
naive_first_id = snapshot['items']['data'][0]['id']
check(naive_first_id == ADDON and naive_first_id != selected['id'], 'Response index zero is the add-on fixture')

cases = [
    ('missing_item_id', {'items': [{'price': NEW_PRICE, 'quantity': 7}]}, 'existing_item_identity_review'),
    ('none_item_id', {'items': [complete_item(id=None)]}, 'existing_item_identity_review'),
    ('explicit_item_and_quantity', {'items': [complete_item()]}, 'ready_prepared_existing_item'),
    ('missing_quantity', {'items': [{'id': CORE, 'price': NEW_PRICE}]}, 'preserved_quantity_review'),
    ('none_quantity', {'items': [complete_item(quantity=None)]}, 'preserved_quantity_review'),
    ('string_quantity', {'items': [complete_item(quantity='7')]}, 'quantity_type_review'),
    ('boolean_quantity', {'items': [complete_item(quantity=True)]}, 'quantity_type_review'),
    ('float_quantity', {'items': [complete_item(quantity=7.0)]}, 'quantity_type_review'),
    ('zero_quantity', {'items': [complete_item(quantity=0)]}, 'quantity_change_review'),
    ('wrong_addon_identity', {'items': [complete_item(id=ADDON)]}, 'existing_item_identity_review'),
    ('duplicate_flat_identity', {'items': [complete_item()], 'items[0][id]': ADDON}, 'duplicate_form_key_review'),
    ('empty_item_id', {'items': [complete_item(id='')]}, 'existing_item_identity_review'),
    ('missing_new_price', {'items': [{'id': CORE, 'quantity': 7}]}, 'price_intent_review'),
    ('two_requested_changes', {'items': [complete_item(), {'id': ADDON, 'quantity': 1}]}, 'requested_line_count_review'),
    ('mapped_core_after_reorder', {'items': [complete_item(id=selected['id'], quantity=selected['quantity'])]}, 'ready_prepared_existing_item'),
    ('metadata_only', {'metadata': {'erp_line': ERP_LINE}}, 'requested_line_count_review'),
]
for name, params, expected in cases:
    original = deepcopy(params)
    pairs = list(_api_encode(params))
    NATIVE_CALLS += 1
    # Same V1 stdlib form step read in the released requestor; no requestor method is called.
    form = urlencode(pairs).replace('%5B', '[').replace('%5D', ']')
    fields = parse_qsl(form, keep_blank_values=True)
    decision = local_decision(params, fields)
    check(params == original, name + ': native encoder did not mutate inputs')
    check(fields == [(key, str(value)) for key, value in pairs], name + ': form round-trip preserves all pairs')
    check(decision == expected, name + ': explicit local intent decision')
    observation = {'case': name, 'params': params, 'form': form, 'wireFields': fields,
                   'decision': decision, 'nativeEncoderCalled': True}
    if name == 'mapped_core_after_reorder':
        observation['naiveFirstResponseItemId'] = naive_first_id
        observation['approvedMappedItemId'] = selected['id']
    if name == 'duplicate_flat_identity':
        observation['naiveDictionaryIdentity'] = dict(fields)['items[0][id]']
    OBSERVATIONS.append(observation)

wrong_subscription = deepcopy(snapshot)
wrong_subscription['id'] = 'sub_DEMO_OTHER_50'
incomplete = deepcopy(snapshot)
incomplete['items']['has_more'] = True
second_binding = dict(binding, itemId=ADDON)
for name, state, bindings, expected in [
    ('missing_erp_binding', snapshot, [], 'binding_missing_review'),
    ('ambiguous_erp_binding', snapshot, [binding, second_binding], 'binding_ambiguous_review'),
    ('incomplete_item_collection', incomplete, [binding], 'selection_incomplete_review'),
    ('wrong_subscription_context', wrong_subscription, [binding], 'subscription_identity_review'),
]:
    item, reason = choose_current_item(state, bindings)
    check(item is None and reason == expected, name + ': local selection guard')
    OBSERVATIONS.append({'case': name, 'decision': reason, 'nativeEncoderCalled': False})

by_name = {row['case']: row for row in OBSERVATIONS}
field_values = lambda name, key: [value for field, value in by_name[name]['wireFields'] if field == key]
check(field_values('missing_item_id', 'items[0][id]') == [], 'Missing item identity is absent on wire')
check(field_values('none_item_id', 'items[0][id]') == [], 'None item identity is omitted by native encoder')
check(field_values('missing_quantity', 'items[0][quantity]') == [], 'Missing quantity remains absent')
check(field_values('none_quantity', 'items[0][quantity]') == [], 'None quantity is omitted')
check(field_values('string_quantity', 'items[0][quantity]') == ['7'], 'String and integer seven can look identical on wire')
check(field_values('explicit_item_and_quantity', 'items[0][quantity]') == ['7'], 'Explicit integer seven is present')
check(field_values('duplicate_flat_identity', 'items[0][id]') == [CORE, ADDON], 'Both duplicate identity fields really exist')
check(by_name['duplicate_flat_identity']['naiveDictionaryIdentity'] == ADDON, 'Local dict collapse loses the first value; no Stripe parser claim')
check(NATIVE_CALLS == 16 and len(OBSERVATIONS) == 20, 'Actual execution counts')
print(json.dumps({'stripeVersion': importlib.metadata.version('stripe'), 'checksPassed': CHECKS,
                  'cases': len(OBSERVATIONS), 'nativeEncoderCalls': NATIVE_CALLS,
                  'localSelectionGuards': 4, 'observations': OBSERVATIONS,
                  'stripeApiCalls': 0, 'realSubscriptionsChanged': 0, 'chargesCreated': 0,
                  'stripeServerValidated': False, 'prorationCalculated': False,
                  'duplicateServerParsingAssumed': False}, ensure_ascii=False, indent=2))
