import sys
import typing

import httpx

def main():
	from_jwt, empire_uuid, to_jwt = sys.argv[1:]

	with httpx.Client(headers={'Authorization': 'Bearer ' + from_jwt}) as from_client:
		empire: typing.Sequence[EmpirePlan] = from_client.get('https://api.prunplanner.org/baseplanner/empire/' + empire_uuid).raise_for_status().json()
		shared: typing.Mapping[str, str] = {s['plan_uuid']: s['shared_uuid']
				for s in from_client.get('https://api.prunplanner.org/shared/list').raise_for_status().json()}
		for plan in empire:
			if plan['uuid'] not in shared:
				print('sharing', plan['uuid'], plan['name'])
				from_client.put('https://api.prunplanner.org/shared/baseplanner/' + plan['uuid']).raise_for_status()
		# refresh shared UUIDs
		shared: typing.Mapping[str, str] = {s['plan_uuid']: s['shared_uuid']
				for s in from_client.get('https://api.prunplanner.org/shared/list').raise_for_status().json()}

	to_client = httpx.Client(headers={'Authorization': 'Bearer ' + to_jwt})
	for plan in empire:
		print('cloning', plan['uuid'], plan['name'])
		shared_uuid = shared[plan['uuid']]
		to_client.put(f'https://api.prunplanner.org/shared/baseplanner/{shared_uuid}/clone').raise_for_status()
		cloned_plan, = (p for p in to_client.get('https://api.prunplanner.org/baseplanner/').raise_for_status().json() if p['name'].startswith('(Shared) '))
		rename_plan(to_client, cloned_plan['uuid'], plan['name'])

def rename_plan(client: httpx.Client, uuid: str, new_name: str) -> None:
	plan = client.get('https://api.prunplanner.org/baseplanner/' + uuid).raise_for_status().json()
	plan['name'] = new_name
	plan.update(plan.pop('baseplanner_data'))
	del plan['empires']
	client.patch('https://api.prunplanner.org/baseplanner/' + uuid, json=plan).raise_for_status()

class EmpirePlan(typing.TypedDict):
	uuid: str
	name: str

if __name__ == '__main__':
	main()
