"""QuestFakeItem availability only for a source-bound crafting ingredient.

This is separate from acquisition/use objective counters and Consumable bags.
No input, native call, process access, or quantity rewrite occurs here.
"""
from copy import deepcopy


def source_fake_material(item):
    from .craft_observer import craft_sources
    binding=item.get('source_material_binding') or {}
    if item.get('table_domain')!='QuestFakeItemSheet' or type(item.get('item_id')) is not int:
        raise ValueError('fake_material_exact_QuestFakeItemSheet_identity_required')
    rows=[r for r in craft_sources()['recipes']['recipes'] if r['id']==binding.get('recipe_id')]
    if len(rows)!=1 or rows[0]['source_ref']!=binding.get('source_ref'):
        raise ValueError('fake_material_current_source_recipe_binding_required')
    recipe=rows[0]
    needs=[r for r in recipe['fake_item_ingredients'] if r['raw_id']==item['item_id'] and r['display_name']==item.get('name')]
    if len(needs)!=1:raise ValueError('fake_material_exact_source_recipe_ingredient_required')
    return recipe,needs[0]


def fake_material_inventory(item,snapshot,*,parent_node_id):
    """Current Amount is usable only in this exact source ingredient context."""
    from .objective_inventory import current_fake_item_stock,fake_item_goal_protection
    from .goal_reservations import goal_commitment_for_item
    recipe,need=source_fake_material(item)
    stock=current_fake_item_stock(item,snapshot)
    if stock['status']!='observed':raise ValueError('fake_material_current_QuestFakeItemSheet_stock_unknown:'+','.join(stock['missing']))
    if stock.get('use_target') is not False:raise ValueError('fake_material_current_use_target_protected')
    protection=fake_item_goal_protection(item,snapshot,exclude_node_id=parent_node_id)
    if protection['status']!='clear':raise ValueError('fake_material_other_current_goal_'+protection['status'])
    commitment=goal_commitment_for_item(snapshot,item,exclude_node_id=parent_node_id)
    amount=commitment['required_quantity']
    if type(amount) is not int or amount<0:raise ValueError('fake_material_goal_commitment_quantity_invalid')
    return dict(status='available',item=deepcopy(item),quantity=stock['quantity'],available_quantity=stock['quantity'],
        uncommitted_quantity=max(0,stock['quantity']-amount),goal_commitment=commitment,
        current_reference_protection=protection,stock_evidence=stock,
        source_material_binding=deepcopy(item['source_material_binding']),source_material=deepcopy(need),
        inventory_scope='current_QuestFakeItemInfo.Amount_for_exact_native_craft_ingredient',
        identity_binding='exact_QuestFakeItemSheet_ID_and_current_source_name; native_Amount',
        complete_inventory=True,inventory_quantity_modified=False,
        permitted_action='source_recipe_material_stock_check; craft_confirm_requires_current_UI_recheck',
        **stock['observation'])
