"""Static fakeitem display-token identity. Never a runtime action predicate."""
from copy import deepcopy
import hashlib
import json
from .paths import root


def resolve_fakeitem_token(target):
    from .objective_inventory import inventory_definitions
    result=dict(resolved=False,static_only=True,gameplay_semantics_resolved=False,
        acquisition_method=None,required_quantity=None,current_stock=None,missing=[])
    if target.get('kind')!='fakeitem':return dict(result,missing=['not_a_fakeitem_token'])
    args=target.get('arguments')
    if not isinstance(args,list) or len(args) not in (1,2) or any(not isinstance(a,str) or not a.strip() for a in args):
        return dict(result,missing=['fakeitem_token_symbol_arity'])
    args=[a.strip() for a in args];quest_symbol=args[0] if len(args)==2 else None;symbol=args[-1]
    rows=[r for r in inventory_definitions()['fake']['items'] if r['fake_item_id']==symbol]
    if len(rows)!=1:return dict(result,quest_symbol=quest_symbol,item_symbol=symbol,
        missing=['fakeitem_symbol_not_unique_in_current_QuestFakeItemSheet'])
    row=rows[0];path=root()/'data/arbeit-craft/fake-items.json'
    return dict(result,resolved=True,quest_symbol=quest_symbol,item_symbol=symbol,
        preserved_token=deepcopy(target),identity=dict(table_domain='QuestFakeItemSheet',item_id=row['raw_id'],name=row['display_name'],symbol=symbol),
        source_refs=[deepcopy(row['source_ref']),deepcopy((target.get('identity_resolution') or {}).get('source_ref'))],
        definition_artifact='data/arbeit-craft/fake-items.json',definition_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),
        missing=['current_owned_typed_objective_action_and_target','current_native_objective_effect'])


def static_fake_identity_index():
    path=root()/'data/arbeit-catalog.json';catalog=json.loads(path.read_text('utf8'));rows=[]
    for quest in catalog['quests']:
        for step in quest['steps']:
            for index,objective in enumerate(step['objectives']):
                for target in objective.get('targets',[]):
                    if target.get('kind')=='fakeitem':
                        rows.append(dict(quest_id=quest['id'],step_id=step['id'],objective_index=index,
                            objective_source_ref=deepcopy(objective['source_ref']),resolution=resolve_fakeitem_token(target)))
    return dict(schema='masukja.static-fakeitem-identities.v1',rows=rows,count=len(rows),
        resolved_count=sum(r['resolution']['resolved'] for r in rows),static_only=True,
        source_catalog_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),catalog_modified=False,game_inputs=0,
        runtime_action_types_inferred=0,quantity_goals_inferred=0)
