"""Inventory public Kaggle file metadata without using account credentials."""
import json,time,urllib.parse,urllib.request
from pathlib import Path
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/r46';URL='https://www.kaggle.com/api/v1/datasets/list/huseyingunduz/diatom-dataset'

def main():
 destination=OUT/'inventory.json'
 if destination.exists():raise FileExistsError('Inventory already exists')
 entries=[];token=None;seen=set()
 for page in range(1,100):
  query={'pageSize':200}
  if token:query['pageToken']=token
  request=urllib.request.Request(URL+'?'+urllib.parse.urlencode(query),headers={'User-Agent':'diatom-research-public-dataset-audit/1.0'})
  with urllib.request.urlopen(request,timeout=40) as r:data=json.load(r)
  if data.get('hasErrorMessage'):raise ValueError('Dataset listing error')
  files=data.get('datasetFiles');
  if not isinstance(files,list):raise ValueError('Invalid dataset file list')
  entries.extend({'name':x['name'],'bytes':x['totalBytes']} for x in files)
  print(f'Page {page}: {len(entries)} public file entries',flush=True)
  next_token=data.get('nextPageToken')
  if not next_token:break
  if next_token in seen:raise ValueError('Repeated listing token')
  seen.add(next_token);token=next_token
 else:raise ValueError('Dataset listing exceeded page limit')
 if len({x['name'] for x in entries})!=len(entries):raise ValueError('Duplicate filenames in listing')
 OUT.mkdir(parents=True,exist_ok=True)
 destination.write_text(json.dumps({'format':'r46-kaggle-file-inventory-v1','source':'https://www.kaggle.com/datasets/huseyingunduz/diatom-dataset','license':'CC BY-NC-SA 4.0 as stated by dataset metadata','files':entries},indent=2)+'\n')
 print('Public file inventory completed.',flush=True)
if __name__=='__main__':main()
