#!/usr/bin/env python3
"""Reproducible mobile API design study. Synthetic inputs; no network or user data.

The gate is an executable specification over trusted fixture state, not a
cryptographic implementation, OAuth stack, production server or benchmark.
"""
import argparse,copy,csv,hashlib,json,os
from pathlib import Path
os.environ.setdefault('MPLCONFIGDIR','/tmp/tensorfact-matplotlib')
ROOT=Path(__file__).resolve().parents[1]
SLUG='mobile-api-security'

def digest(payload):
    # Fixed ASCII, integer-only fixtures. This is NOT an implementation of JCS.
    return hashlib.sha256(json.dumps(payload,sort_keys=True,separators=(',',':'),ensure_ascii=True).encode()).hexdigest()

def gate(intent,current,payload,ledger):
    if not current['token_valid'] or not current['object_allowed']:return 'unauthorised'
    if not current['session_active']:return 'session_closed'
    if intent['actor']!=current['actor'] or intent['tenant']!=current['tenant']:return 'context_changed'
    if intent['epoch']!=current['epoch']:return 'epoch_changed'
    if intent['purpose']!=current['purpose']:return 'purpose_changed'
    if not current['purpose_allowed']:return 'purpose_withdrawn'
    # Compare with trusted fixture intent. Client-supplied digests alone prove nothing.
    h=digest(payload)
    if h!=intent['body_digest']:return 'body_changed'
    if not set(payload)<=current['allowed_fields']:return 'field_denied'
    key=(current['actor'],current['tenant'],intent['operation'])
    if key in ledger:return 'cached' if ledger[key]==h else 'idempotency_conflict'
    if current['now']>=intent['deadline']:return 'intent_expired'
    if intent['resource_version']!=current['resource_version']:return 'resource_changed'
    ledger[key]=h
    return 'committed'

def fixtures():
    payload={'record':7,'value':42}
    intent={'actor':'user-a','tenant':'tenant-a','epoch':4,'purpose':'field-report','operation':'op-1','body_digest':digest(payload),'resource_version':8,'deadline':300}
    current={'actor':'user-a','tenant':'tenant-a','epoch':4,'purpose':'field-report','now':100,'token_valid':True,'object_allowed':True,'purpose_allowed':True,'session_active':True,'allowed_fields':{'record','value'},'resource_version':8}
    scenarios=[]
    def add(name,change=None,body=None,ledger=None,attempts=1,expected='committed',intent_change=None):
        state=copy.deepcopy(current);state.update(change or {})
        bound_intent=copy.deepcopy(intent);bound_intent.update(intent_change or {})
        scenarios.append((name,bound_intent,state,copy.deepcopy(body if body is not None else payload),copy.deepcopy(ledger or {}),attempts,expected))
    add('valid_submit')
    add('identical_network_retry',attempts=2,expected='cached')
    add('invalid_token',{'token_valid':False},expected='unauthorised')
    add('object_not_authorised',{'object_allowed':False},expected='unauthorised')
    add('account_switch',{'actor':'user-b'},expected='context_changed')
    add('tenant_switch',{'tenant':'tenant-b'},expected='context_changed')
    add('policy_epoch_advanced',{'epoch':5},expected='epoch_changed')
    add('purpose_withdrawn',{'purpose_allowed':False},expected='purpose_withdrawn')
    add('resource_changed',{'resource_version':9},expected='resource_changed')
    add('intent_deadline_reached',{'now':300},expected='intent_expired')
    add('body_changed',body={'record':7,'value':43},expected='body_changed')
    add('session_closed',{'session_active':False},expected='session_closed')
    add('sensitive_field_not_allowed',{'allowed_fields':{'record'}},expected='field_denied')
    add('same_operation_conflicting_body',ledger={('user-a','tenant-a','op-1'):'different-digest'},expected='idempotency_conflict')
    add('retry_after_session_closed',{'session_active':False},ledger={('user-a','tenant-a','op-1'):digest(payload)},expected='session_closed')
    add('purpose_changed',{'purpose':'different-purpose'},expected='purpose_changed')
    completed={('user-a','tenant-a','op-1'):digest(payload)}
    add('completed_retry_after_deadline',{'now':301},ledger=completed,expected='cached')
    add('completed_retry_after_resource_update',{'resource_version':9},ledger=completed,expected='cached')
    add('explicitly_reviewed_new_context',{'epoch':5},intent_change={'epoch':5})
    add('separate_tenant_operation',{'tenant':'tenant-b'},ledger=completed,intent_change={'tenant':'tenant-b'})
    return scenarios

def run_cases():
    rows=[]
    for name,intent,state,body,ledger,attempts,expected in fixtures():
        strict_commits=0;outcome=''
        for _ in range(attempts):
            outcome=gate(intent,state,body,ledger)
            strict_commits+=outcome=='committed'
        assert outcome==expected,(name,outcome,expected)
        rows.append([name,attempts,expected,strict_commits,outcome])
    return rows

def revocation_traces():
    """Enumerate all check-before-write orderings for one explicit invalidation.

    State transitions are sequential model steps, not a database concurrency test.
    """
    rows=[]
    for order in [('revoke','check','write'),('check','revoke','write'),('check','write','revoke')]:
        for policy in ['entry_check_only','recheck_at_write']:
            active=True;permitted=None
            for step,event in enumerate(order,1):
                decision=''
                if event=='revoke':active=False
                elif event=='check':permitted=active
                else:decision='committed' if permitted and (active or policy=='entry_check_only') else 'rejected'
                rows.append(['>'.join(order),policy,step,event,int(active),decision])
    return rows

def main():
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--output',type=Path);args=parser.parse_args()
    out=args.output or (ROOT/'public/research-assets'/SLUG if (ROOT/'app/data/research.json').exists() else Path.cwd()/'mobile-api-results');out.mkdir(parents=True,exist_ok=True)
    import numpy as np
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    from matplotlib.patches import FancyBboxPatch,FancyArrowPatch
    from matplotlib.colors import ListedColormap
    plt.rcParams.update({'font.family':'DejaVu Sans','font.size':10,'svg.fonttype':'none','svg.hashsalt':'mobile-api-v1.1','axes.spines.top':False,'axes.spines.right':False,'text.color':'#244556','axes.labelcolor':'#244556'})
    def save(fig,name):
        fig.savefig(out/(name+'.svg'),metadata={'Date':None});fig.savefig(out/(name+'.png'),dpi=180);plt.close(fig)
        p=out/(name+'.svg')
        # Browser hosts may not have DejaVu installed; keep an explicit sans-serif fallback.
        svg=p.read_text().replace("'DejaVu Sans'","'DejaVu Sans', Arial, sans-serif")
        p.write_text('\n'.join(x.rstrip() for x in svg.splitlines())+'\n')
    def csvout(name,head,rows):
        with (out/name).open('w',newline='') as f:w=csv.writer(f,lineterminator='\n');w.writerow(head);w.writerows(rows)
    cases=run_cases();csvout('scenario-results.csv',['scenario','attempts','expected_outcome','new_mutations','observed_outcome'],cases)
    traces=revocation_traces();csvout('revocation-traces.csv',['event_order','check_design','step','event','session_active','decision'],traces)
    events=[['09:00','Draft created','Account A / purpose P / prior server context'],['09:30','Policy changes','Prior context requires renewed review'],['10:59:30','Credential issued','Current identity; old draft remains unchanged'],['11:00','Submission attempted','Check original context and present authority']]
    csvout('illustrative-timeline.csv',['illustrative_time','event','meaning'],events)
    fig,ax=plt.subplots(figsize=(11,4.8));ax.axis('off');ax.set_title('Illustrative reconnect events: token age and intent age differ',loc='left',pad=18)
    for i,(time,event,meaning) in enumerate(events):
        y=.78-i*.2;ax.plot([.055,.055],[y-.2 if i<3 else y,y],color='#86aa9e',lw=2);ax.scatter([.055],[y],color='#315f73',s=50,zorder=3);ax.text(.1,y+.015,time+'  /  '+event,weight='bold',fontsize=11);ax.text(.1,y-.065,meaning,fontsize=10)
    ax.text(.02,-.02,'Authored example, not observations. At 11:00: draft age = 2 hours; token age = 30 seconds.\nAn old draft may remain permitted; the required decision depends on current policy and context.',fontsize=9.5);ax.set(xlim=(0,1),ylim=(-.1,1));fig.subplots_adjust(left=.03,right=.98,top=.86,bottom=.12);save(fig,'context-timeline')
    # Every row is the outcome of one explicit fixture. No percentages or attack-rate inference.
    labels=[r[0].replace('_',' ') for r in cases];values=np.array([[0 if r[4]=='committed' else 1 if r[4]=='cached' else 2] for r in cases])
    fig,ax=plt.subplots(figsize=(11,9.2));ax.imshow(values,aspect='auto',cmap=ListedColormap(['#cfe3d8','#d5e4f0','#f2e5d2']),vmin=0,vmax=2)
    for i,r in enumerate(cases):ax.text(0,i,r[4].replace('_',' '),ha='center',va='center',fontsize=10)
    ax.set_yticks(range(len(cases)),labels=labels,fontsize=9.5);ax.set_xticks([]);ax.tick_params(axis='y',length=0);ax.set_title('Reference-model outcomes for named fixtures',pad=20)
    for edge in ax.spines.values():edge.set_visible(False)
    ax.text(-.02,-.075,'Green: new mutation   /   Blue: existing outcome   /   Sand: rejected\nAuthored sequential fixtures; no real-device, cryptographic or distributed implementation is evaluated.',transform=ax.transAxes,fontsize=9.5,ha='left');fig.subplots_adjust(left=.37,right=.98,top=.92,bottom=.12);save(fig,'scenario-matrix')
    handling=[['Access token','Scoped use','No','Scoped use','No'],['Refresh token','Token flow only','No','No','No'],['Sensitive business payload','Minimum','Encrypted draft','Minimum','No'],['Policy / operation identifiers','Scoped','Scoped','Scoped','Minimised'],['Outcome / error category','Permitted','Minimum','Permitted','Permitted']]
    csvout('proposed-data-handling.csv',['data_class','app_memory','protected_queue','resource_api','diagnostics'],handling)
    fig,ax=plt.subplots(figsize=(11,5));ax.axis('off');ax.set_title('Proposed data-handling map for the example workflow',loc='left',pad=20)
    tab=ax.table(cellText=handling,colLabels=['Data class','App memory','Protected queue','Resource API','Diagnostics'],cellLoc='left',colLoc='left',colWidths=[.28,.19,.19,.17,.17],bbox=[0,.2,1,.7]);tab.auto_set_font_size(False);tab.set_fontsize(9)
    for (row,col),cell in tab.get_celld().items():
        cell.set_edgecolor('#cedbd4');cell.set_facecolor('#e4eee7' if row==0 else '#f5f8f5');cell.set_text_props(color='#244556',weight='bold' if row==0 else 'normal')
    ax.text(0,.04,'Design proposal, not a measured dataset or universal platform rule. “Minimum” means purpose-limited.\nRefresh tokens go to the authorisation server, not the resource API. Minimise metadata and protect its access.\nNo raw tokens or business payloads in diagnostics; evaluate actual SDKs, backups and recipients separately.',fontsize=9.3);fig.subplots_adjust(left=.03,right=.98,top=.85,bottom=.04);save(fig,'sensitive-data-map')
    def box(ax,x,y,w,h,title,lines):
        ax.add_patch(FancyBboxPatch((x,y),w,h,boxstyle='round,pad=0.012',ec='#83a89a',fc='#edf4ef',lw=1.2));ax.text(x+.018,y+h-.045,title,fontsize=11,weight='bold',va='top');ax.text(x+.018,y+h-.105,lines,fontsize=9.5,va='top',linespacing=1.6)
    def arrow(ax,a,b,label=None):
        ax.add_patch(FancyArrowPatch(a,b,arrowstyle='-|>',mutation_scale=13,color='#527e72',lw=1.4))
        if label:ax.text((a[0]+b[0])/2,(a[1]+b[1])/2+.025,label,ha='center',fontsize=9)
    fig,ax=plt.subplots(figsize=(11,6));ax.set(xlim=(0,1),ylim=(0,1));ax.axis('off');ax.set_title('Mobile API trust boundaries and data paths',loc='left',pad=15)
    box(ax,.02,.52,.26,.33,'Mobile device','UI and account context\nProtected local queue\nPlatform key custody')
    box(ax,.38,.52,.25,.33,'API boundary','TLS terminates here\nToken + proof validation\nRate and size limits')
    box(ax,.72,.52,.26,.33,'Commit boundary','Current policy + purpose\nContext + version check\nAtomic ledger and write')
    arrow(ax,(.29,.69),(.37,.69),'TLS');arrow(ax,(.64,.69),(.71,.69),'Protected hop')
    box(ax,.38,.12,.25,.23,'Identity / policy','Session and role epoch\nConsent / purpose state');arrow(ax,(.51,.36),(.79,.51))
    box(ax,.72,.12,.26,.23,'Diagnostics','Allowlisted metadata\nNo tokens or payloads');arrow(ax,(.85,.51),(.85,.36))
    ax.text(.02,.04,'TLS protects a connection. Decrypted processing, queues, logs and downstream copies have separate boundaries.',fontsize=10);fig.subplots_adjust(left=.03,right=.98,top=.93,bottom=.03);save(fig,'trust-boundaries')
    fig,ax=plt.subplots(figsize=(11,5.3));ax.set(xlim=(0,1),ylim=(0,1));ax.axis('off');ax.set_title('A safe reconnect sequence for queued mutations',loc='left',pad=15)
    labels=[('QUEUE', 'Bind account, tenant\nand prior server context'),('RECONNECT','Obtain current credentials\nDo not rewrite old context'),('REVIEW','Check deadline, purpose\nand confirmation needs'),('COMMIT','Check current authority\nDeduplicate atomically')]
    for i,(title,lines) in enumerate(labels):
        x=.025+i*.25;box(ax,x,.48,.21,.32,title,lines)
        if i<3:arrow(ax,(x+.222,.64),(x+.238,.64))
    ax.text(.04,.29,'Mismatch → preserve only a permitted draft; require review or reject. Never silently adopt a new account.',fontsize=10)
    ax.text(.04,.17,'Unknown commit result → retry the same operation identifier and digest; recheck authority before returning data.',fontsize=10)
    ax.text(.04,.05,'A local timestamp or hash is not proof of user intent. Server-authenticated context and trustworthy confirmation matter.',fontsize=9.5);fig.subplots_adjust(left=.03,right=.98,top=.9,bottom=.03);save(fig,'reconnect-sequence')
    results={'scenario_count':len(cases),'attempt_count':sum(r[1] for r in cases),'new_mutations':sum(r[3] for r in cases),'rejected_cases':sum(r[4] not in ['committed','cached'] for r in cases),'cached_outcome_cases':sum(r[4]=='cached' for r in cases),'revocation_orderings':3}
    manifest={'model_version':'1.1','study_type':'Sequential reference-model checks, not empirical mobile/API measurements','results':results,'assumptions':['Fixture intent and policy state are trusted inputs. Cryptographic verification, attestation, user confirmation and capability issuance are not implemented.','Each named case starts with independent state except its specified repeat attempts or prepopulated operation ledger.','Policy check and mutation are one sequential model step; real distributed atomicity and race protection remain untested.','The three revocation traces enumerate check-before-write event orderings, not arrival probabilities or production performance.','The event timeline is an authored example. The data-handling map is an authored policy proposal.'],'exclusions':['No breach probabilities, prevalence, latency, battery, device testing, cryptographic assurance or product comparison.','Version 1.0 arithmetic charts were internally correct but restated assumptions and did not justify real-world quantitative conclusions; they are removed in this revision.'],'software':{'numpy':np.__version__,'matplotlib':matplotlib.__version__}}
    (out/'model-parameters.json').write_text(json.dumps(manifest,indent=2)+'\n');print(json.dumps(results,indent=2))
if __name__=='__main__':main()
