# this code is a bit of a mess, because I don't usually use Python. sorry...

import json
import urllib.request
import urllib.error

storiesquery = {
	"variables": {
		"input": {
			"searchTerm": "",
			"saved": False,
			"trash": False,
			"contentType": "adventure",
			"sortOrder": "createdAt",
			"offset": 0
		}
	},
	"query": """
query ($input: SearchInput) {
	user {
		search(input: $input) {
			...ContentCardSearchable
		}
	}
}
fragment ContentCardSearchable on Adventure {
	id
	publicId
	title
	description
	createdAt
	updatedAt
	type
	score
	memory
	authorsNote
	score
	isOwner
	
	user {
		username
	}
	
	actions {
		...ActionSubscriptionAction
	}

	undoneWindow {
		...ActionSubscriptionAction
	}
}

fragment ActionSubscriptionAction on Action {
	id
	text
	type
	createdAt
}
""".replace('\t', '')
}

ccs = """
fragment ContentCardSearchable on Scenario {
	id
	publicId
	title
	description
	tags
	createdAt
	updatedAt
	memory
	authorsNote
	mode
	prompt
	quests
	gameCode
	isOwner
	
	user {
		username
	}
	
	options {
		publicId
		title
		createdAt
	}
}
"""

scenariosquery = {
	"variables": {
		"input": {
			"searchTerm": "",
			"saved": False,
			"trash": False,
			"contentType": "scenario",
			"sortOrder": "createdAt",
			"offset": 0
		}
	},
	"query": ("""
query ($input: SearchInput) {
	user {
		id
		search(input: $input) {
			...ContentCardSearchable
		}
	}
}
""" + ccs).replace('\t', '')
}
	
subscenquery = {
	"variables": {
		"publicId": ""
	},
	"query": ("""
query ($publicId: String) {
	scenario(publicId: $publicId) {
		...ContentCardSearchable
	}
}
""" + ccs).replace('\t', '')
}

key = input('Please enter your token: ')
dosaved = input('Should I grab your bookmarks as well? (Y/N) ')
out = {"stories": [], "scenarios": []}
subscen = []

def grabstories():
	storiesquery['variables']['input']['offset'] = 0
	while True:
		print('Getting a page of stories...')
		req = urllib.request.Request('https://api.aidungeon.io/graphql', headers={"x-access-token": key, "content-type": "application/json"})
		res = None
		
		try:
			res = urllib.request.urlopen(req, data=json.dumps(storiesquery).encode('utf8'))
		except urllib.error.HTTPError as e:
			print(e)
			print(e.read())
			break
		
		result = json.load(res)
		
		if 'data' in result and 'user' in result['data'] and 'search' in result['data']['user']:
			if len(result['data']['user']['search']) > 0:
				out['stories'] += result['data']['user']['search']
				storiesquery['variables']['input']['offset'] += len(result['data']['user']['search'])
				print('Got %d stories so far' % storiesquery['variables']['input']['offset'])
			else:
				print('Looks like there\'s no more.')
				break
		else:
			print('There was no data...')
			print(result)
			break

	scenariosquery['variables']['input']['offset'] = 0
	while True:
		print('Getting a page of scenarios...')
		req = urllib.request.Request('https://api.aidungeon.io/graphql', headers={"x-access-token": key, "content-type": "application/json"})
		res = None
		
		try:
			res = urllib.request.urlopen(req, data=json.dumps(scenariosquery).encode('utf8'))
		except urllib.error.HTTPError as e:
			print(e)
			print(e.read())
			break
		
		result = json.load(res)
		
		if 'data' in result:
			if len(result['data']['user']['search']) > 0:
				out['scenarios'] += result['data']['user']['search']
				scenariosquery['variables']['input']['offset'] += len(result['data']['user']['search'])
				for scenario in result['data']['user']['search']:
					if 'options' in scenario and type(scenario['options']) is list:
						for option in scenario['options']:
							subscen.append(option['publicId'])
				print('Got %d scenarios so far' % scenariosquery['variables']['input']['offset'])
			else:
				print('Looks like there\'s no more.')
				break
		else:
			print('There was no data...')
			print(result)
			break

grabstories()

if len(dosaved) > 0 and dosaved[0].lower() == 'y':
	storiesquery['variables']['input']['saved'] = True
	scenariosquery['variables']['input']['saved'] = True
	grabstories()

for pubid in subscen:
	print('Getting subscenario %s...' % pubid)
	
	subscenquery['variables']['publicId'] = pubid
	req = urllib.request.Request('https://api.aidungeon.io/graphql', headers={"x-access-token": key, "content-type": "application/json"})
	res = None
	
	try:
		res = urllib.request.urlopen(req, data=json.dumps(subscenquery).encode('utf8'))
	except urllib.error.HTTPError as e:
		print(e)
		print(e.read())
		break
	
	result = json.load(res)
	
	if type(result) is dict and type(result.get('data')) is dict and type(result['data'].get('scenario')) is dict:
		result['data']['scenario']['isOption'] = True
		out['scenarios'].append(result['data']['scenario'])
		if 'options' in result['data']['scenario'] and type(result['data']['scenario']['options']) is list:
			for option in result['data']['scenario']['options']:
				subscen.append(option['publicId'])
	else:
		print('Couldn\'t find that scenario')
		print(result)

outfile = open('stories.json', 'w')
json.dump(out, outfile)
outfile.close()
