from __future__ import annotations

import collections
import sys
import typing

import cache
import integration

def main() -> None:
	code = sys.argv[1]
	company: Company = cache.get('https://rest.fnar.net/company/code/' + code)
	planets = {cp['PlanetName'] for cp in company['Planets']}

	cogc_planets: dict[str, list[str]] = collections.defaultdict(list)
	for planet, cogc in iter_planet_cogc():
		if planet['PlanetName'] in planets:
			print(planet['PlanetName'], cogc, sep='\t\t')
			if cogc is not None:
				cogc_planets[cogc].append(planet['PlanetName'])
	print()

	experts = mat_expertise()
	company_report = integration.pmmg_monthly_report()[company['CompanyId']]
	report_by_expertise: dict[str | None, dict[str, int]] = collections.defaultdict(dict)
	for mat, production in company_report.items():
		expertise = experts.get(mat)
		report_by_expertise[expertise][mat] = production['amount']

	for expertise, sub_report in report_by_expertise.items():
		print(expertise, end=' ')
		if expertise is not None:
			print(', '.join(cogc_planets.get(expertise, [])), end='')
		print()
		for mat, amount in sub_report.items():
			print(f'\t{mat:3} {amount:9,.1f}')

def iter_planet_cogc() -> typing.Iterator[tuple[Planet, Expertise | None]]:
	all_planets: typing.Collection[Planet] = cache.get('https://universemap.taiyibureau.de/planet_data.json',
			expiry=cache.ONE_DAY)
	for planet in all_planets:
		cogc = None
		if len(cogcs := planet['COGCPrograms']) > 1:
			cogcs.sort(key=lambda c: c['StartEpochMs'], reverse=True)
			cogc = cogcs[1]['ProgramType']
			if cogc is not None:
				cogc = cogc.removeprefix('ADVERTISING_')
		yield planet, typing.cast(Expertise | None, cogc)

def mat_expertise() -> dict[str, Expertise]:
	expertise: dict[str, Expertise] = {
		'AL': 'METALLURGY',
		'DRF': 'ELECTRONICS',
		'FE': 'METALLURGY',
	}

	materials: typing.Sequence[Material] = cache.get('https://rest.fnar.net/material/allmaterials', expiry=cache.ONE_DAY)
	for material in materials:
		if material['CategoryName'] in ('ores', 'minerals', 'liquids', 'gases'):
			expertise[material['Ticker']] = 'RESOURCE_EXTRACTION'

	buildings: typing.Sequence[Building] = cache.get('https://rest.fnar.net/building/allbuildings', expiry=cache.ONE_DAY)
	for building in buildings:
		for recipe in building['Recipes']:
			for output in recipe['Outputs']:
				expertise.setdefault(output['CommodityTicker'], building['Expertise'])

	return expertise

Expertise = typing.Literal['AGRICULTURE', 'CHEMISTRY', 'CONSTRUCTION', 'ELECTRONICS', 'FOOD_INDUSTRIES',
	'FUEL_REFINING', 'MANUFACTURING', 'METALLURGY', 'RESOURCE_EXTRACTION']

class Company(typing.TypedDict):
	CompanyId: str
	Planets: typing.Sequence[CompanyPlanet]

class CompanyPlanet(typing.TypedDict):
	PlanetNaturalId: str
	PlanetName: str

class Planet(typing.TypedDict):
	PlanetId: str
	PlanetName: str
	COGCPrograms: list[PlanetCOGC]

class PlanetCOGC(typing.TypedDict):
	ProgramType: str | None
	StartEpochMs: float

class Building(typing.TypedDict):
	Recipes: typing.Sequence[BuildingRecipe]
	Expertise: str

class BuildingRecipe(typing.TypedDict):
	Outputs: typing.Sequence[BuildingMat]

class BuildingMat(typing.TypedDict):
	CommodityTicker: str
	Amount: int

class Material(typing.TypedDict):
	Ticker: str
	CategoryName: str

if __name__ == '__main__':
	main()
