from __future__ import annotations

import collections
import re
import sys
import typing

import cache

if typing.TYPE_CHECKING:
	import roi

def main() -> None:
	mat = sys.argv[1]

	recipes: list[roi.Recipe] = cache.get('https://api.prunplanner.org/data/recipes/')
	companies = pmmg_monthly_report()

	print(mat, '→')
	wrought = (recipe for recipe in recipes
			if mat in (i['material_ticker'] for i in recipe['inputs']) and len(recipe['outputs']) == 1)
	output_mats = {}
	for recipe in sorted(wrought, key=lambda r: r['outputs'][0]['material_ticker']):
		(output,) = recipe['outputs']
		(input,) = (i for i in recipe['inputs'] if i['material_ticker'] == mat)
		ratio = input['material_amount'] / output['material_amount']
		output_mats[output['material_ticker']] = ratio
		print(f'\t{output["material_ticker"]:3}:', ratio)

	companies_produced = companies_consumed = companies_consumed_only = companies_consumed_own = companies_consumed_80_own = 0
	into = dict.fromkeys(output_mats.keys(), 0)
	for company in companies.values():
		if (co_production := company.get(mat)) is not None:
			companies_produced += 1
		consumed = 0
		for output_mat, per_run_consumption in output_mats.items():
			if co_consumption := company.get(output_mat):
				total_consumption = co_consumption['amount'] * per_run_consumption
				consumed += total_consumption
				into[output_mat] += total_consumption
		if consumed > 0:
			companies_consumed += 1
			if co_production is None:
				companies_consumed_only += 1
			else:
				companies_consumed_own += 1
				if consumed > 0.8 * co_production['amount']:
					companies_consumed_80_own += 1
	print(f'{companies_produced} companies producing')
	print(f'{companies_consumed} companies consuming')
	print(f'{companies_consumed_only} companies consuming without producing any')
	print(f'{companies_consumed_own} companies consuming their own production')
	print(f'{companies_consumed_80_own} companies consuming 80%+ of their own production')

	recipes_per_output = collections.defaultdict(int)
	for recipe in recipes:
		for output in recipe['outputs']:
			if output['material_ticker'] in into:
				recipes_per_output[output['material_ticker']] += 1
	for output_mat, total in sorted(into.items(), key=lambda kv: kv[1], reverse=True):
		alt = ''
		if (recipe_count := recipes_per_output[output_mat]) != 1:
			alt = f' ({recipe_count} recipes)'
		print(f'{output_mat:3}: {total:8,.0f}{alt}')

def pmmg_monthly_report() -> dict[str, dict[str, CompanyOutput]]:
	report_constants = cache.get(
			'https://raw.githubusercontent.com/PMMG-Products/pmmg-products.github.io/main/reports/src/staticData/constants.ts',
			json=False, expiry=cache.ONE_DAY)
	# export const months = ["mar25", "apr25", ..., "dec25", "jan26"];
	match = re.search(r'export const months = \[(.*?)\];', report_constants)
	assert match
	months_str = match.group(1)
	months = [m.strip().strip('"') for m in months_str.split(',')]
	last_month = months[-1]
	print('getting report for', last_month)
	return cache.get(f'https://pmmg-products.github.io/reports/data/company-data-{last_month}.json', expiry=cache.ONE_DAY)['individual']

class CompanyOutput(typing.TypedDict):
	amount: int

if __name__ == '__main__':
	main()
