from pathlib import Path
import json, re, subprocess

base = Path(__file__).parent
app = base / 'app'
sha = subprocess.check_output(['git', 'rev-parse', 'HEAD'],cwd=app,text=True).strip()
release = subprocess.check_output(['git', 'rev-parse', 'origin/release/v1.4.7'],cwd=app,text=True).strip()
def src(p): return (app/p).read_text(encoding='utf-8')
def line(p, offset): return src(p)[:offset].count('\n')+1

mobile = {'home':'home/MobileHomeBinding.tsx','calendar':'calendar/MobileCalendarBinding.tsx','feed':'social/MobileFeedBinding.tsx','group':'group/MobileGroupBinding.tsx','challenge':'challenge/MobileChallengeBinding.tsx','leaderboard':'social/MobileLeaderboardBinding.tsx','follows':'social/MobileFollowListBinding.tsx','volume':'volume/MobileVolumeBinding.tsx','search':'search/MobileSetSearchBinding.tsx','routines':'active-workout/MobileRoutinesBinding.tsx','profile':'profile/MobileProfileBinding.tsx'}
desktop = {'home':'home/DesktopHomeBinding.tsx','calendar':'calendar/DesktopCalendarBinding.tsx','logtable':'log-table/DesktopLogTableBinding.tsx','search':'search/DesktopSearchBinding.tsx','favgroups':'favorite-groups/DesktopFavoriteGroupsBinding.tsx','volume':'volume/DesktopVolumeBinding.tsx','pr':'pr/DesktopPrBinding.tsx','profile':'profile/DesktopProfileBinding.tsx'}
routes=[]
for platform,values in [('mobile',mobile),('desktop',desktop)]:
    for name,binding in values.items():
        routes.append({'platform':platform,'tab':name,'binding':'src/react/features/'+binding,'renderBoundary':'FeatureLoadBoundary per tab; ancestor FeatureProviders outside','reviewDepth':'route wiring and read-state path traced; no browser fault injection'})
p='src/react/app/navigation/screenKinds.ts'
stack=[{'kind':m.group(1),'source':p,'line':line(p,m.start()),'reviewDepth':'route registry enumerated; relevant read paths grouped in report','runtimeTested':False} for m in re.finditer(r'^  (\w+): \{',src(p),re.M)]

p='src/react/services/domains/codecs/dataModuleCodec.ts'
s=src(p); start=s.index('const DATA_MODULE_DECODERS:'); end=s.index('const HOME_PERIOD_KEYS')
modules=[]
for m in re.finditer(r'^  "([a-z_]+\.[a-z_]+)":',s[start:end],re.M):
    name=m.group(1)
    modules.append({'name':name,'decoderFile':p,'line':line(p,start+m.start()),'reviewDepth':'decoder entry/common failure shape read; shared request-cache-publication path traced; delegated row predicates not all individually proven','runtimeTested':False,'failureBoundary':'payload decode is module-local in fetchDataModules; envelope validation is batch-wide; caller may aggregate status'})

readers = [
 ('src/react/resources/resourceStore.ts','common resource','source traced'),
 ('src/react/resources/stats/dataModuleResource.ts','all data modules','source traced'),
 ('src/react/resources/stats/dataModuleDemand.ts','module demand/retry','source traced'),
 ('src/react/resources/stats/moduleView.ts','PR/calendar composition','source traced'),
 ('src/react/resources/stats/homeShellModules.ts','home composition','source traced'),
 ('src/react/resources/stats/prOverviewResource.ts','PR overview','source traced'),
 ('src/react/resources/stats/volumeOverviewResource.ts','desktop volume','source traced'),
 ('src/react/resources/stats/homeYearActivityResource.ts','desktop home annual activity','source traced'),
 ('src/react/resources/exerciseCatalogResource.ts','catalog','caller and common resource path; body not fully reviewed'),
 ('src/react/resources/sessionRecordResource.ts','session record','consumer and shared resource traced; record codec body assigned other agent'),
 ('src/react/features/calendar/calendarReadModelStore.ts','calendar month/day/range','source traced'),
 ('src/react/features/calendar/queries/calendarModuleViews.ts','calendar composition','source traced'),
 ('src/react/features/calendar/queries/calendarDayModules.ts','calendar day rows','source traced'),
 ('src/react/features/log-table/logTableStore.ts','log month/cell','source traced'),
 ('src/react/features/pr/queries/prExerciseQueryBinding.ts','exercise initial/year/records/history/archive','readiness, parallel orchestration and consumer traced; not every archive branch'),
 ('src/react/features/pr/queries/prExerciseDetailResource.ts','exercise data resources','call and generation wiring; not every decoder branch'),
 ('src/react/features/workout/history/exerciseHistoryResource.ts','exercise history','call graph and readiness consumer only'),
 ('src/react/features/search/queries/sessionSearchQuery.ts','session search pages','source traced'),
 ('src/react/features/social/feedResource.ts','feed page chain','source traced'),
 ('src/react/features/social/friendScopeStore.ts','friend scope slices/day sessions','source traced'),
 ('src/react/features/group/groupStore.ts','group list/lounge/attendance','read snapshots/request/error handling traced; mutations excluded'),
 ('src/react/features/group/groupBoardStore.ts','board/day sessions/start boards','read snapshots and parallel dependencies traced; mutations excluded'),
 ('src/react/features/challenge/challengeStore.ts','challenge list/detail','read path traced; mutations excluded'),
 ('src/react/features/program/programStore.ts','routine list','read path traced; mutations excluded'),
 ('src/react/features/profile/profileResource.ts','profile','source traced; authentication external'),
 ('src/react/features/notification/notificationTargetStore.ts','notification target session and social metadata','source traced'),
 ('src/react/domain/user/relations.ts','following/followers','followers failure path traced; other user writes excluded'),
 ('src/react/features/recovery/workoutRestoreStore.ts','restore panel source','UI adapter traced; restore aggregate assigned other agent'),
 ('src/react/features/social/feedSocialStore.ts','comments/reactions','route consumer/search only; no complete body review'),
 ('src/react/features/profile/socialIdentityController.ts','social identities','UI region boundary/caller traced; body not fully reviewed'),
]
lazy=[]
for p in ['src/react/ui/mobile/screenModules.tsx','src/react/ui/desktop/screenModules.tsx']:
    for m in re.finditer(r'^const (\w+) = defineScreenModule',src(p),re.M):
        lazy.append({'module':m.group(1),'source':p,'line':line(p,m.start()),'reviewDepth':'registry and shared code-load rejection handling traced','runtimeTested':False})
result={'issue':'https://github.com/dekerd/Barbelic/issues/2503','mainCommit':sha,'releaseCommit':release,'scope':'UI read/render fault boundaries; audit only','reviewDefinitions':{'source traced':'read actual implementation and connect producer→consumer→UI; no claim of browser/Production execution','enumerated':'complete population listing or shared-boundary scan, not function correctness review'},'routes':routes,'stackKinds':stack,'dataModules':modules,'readBoundaries':[{'path':p,'responsibility':r,'reviewDepth':d,'runtimeTested':False} for p,r,d in readers],'lazyScreenModules':lazy,'syntheticEvidence':'ui-probe-results.json','excluded':['authentication and boot state implementation (separate agent)','write/outbox/database/server implementation (separate agents)','visual CSS correctness','Production/device reproduction','full QA2/unit suite'],'releaseChangedUiFiles':subprocess.check_output(['git','diff','--name-only','HEAD','origin/release/v1.4.7','--','src/react'],cwd=app,text=True).splitlines()}
(base/'ui-inventory.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps({k:len(result[k]) for k in ['routes','stackKinds','dataModules','readBoundaries','lazyScreenModules']},ensure_ascii=False))
