"""Reproduce Episode 030's historical counts from Statistics Denmark."""

import csv
from collections import Counter
from urllib.parse import urlencode
from urllib.request import urlopen


def counts(table, permit_codes, include_sex=False):
    filters = {"lang": "en", "STATSB": "5448", "Tid": "2024", "OPHOLD": permit_codes}
    if include_sex:
        filters["KOEN"] = "1,2"
    url = f"https://api.statbank.dk/v1/data/{table}/CSV?{urlencode(filters)}"
    with urlopen(url, timeout=15) as response:
        rows = csv.DictReader(response.read().decode("utf-8-sig").splitlines(), delimiter=";")
    totals = Counter()
    series = set()
    for row in rows:
        category, sex = row["OPHOLD"], row.get("KOEN")
        if (row["STATSB"], row["TID"]) != ("China", "2024") or (category, sex) in series:
            raise ValueError(f"Unexpected series in {table}. Check the official response.")
        series.add((category, sex))
        totals[category] += int(row["INDHOLD"])
    print(f"{table}  {url}")
    return totals, series


def main():
    workers = "Work, fast-track, pay limit scheme"
    family = "Work, dependent family members"
    eea = "EU/EEA, wage-earners"
    arrivals, arrival_series = counts("VAN8A", "105,106,7", include_sex=True)
    permanent, permanent_series = counts("VAN66P", "9")
    expected_arrivals = {(category, sex) for category in (workers, family, eea) for sex in ("Men", "Women")}
    if arrival_series != expected_arrivals or permanent_series != {("Work", None)}:
        raise ValueError("One or more requested official series were not returned.")

    print("\n2024 | Chinese citizenship | Statistics Denmark")
    for category in (workers, family, eea):
        print(f"VAN8A  {category:<34}  {arrivals[category]:>4}")
    print(f"VAN8A  Work-related arrivals combined      {sum(arrivals.values()):>4}")
    print(f"VAN66P Permanent residence, Work category  {permanent['Work']:>4}")
    print("\nConversion rate: NOT ESTIMABLE — these tables do not follow the same people.")


if __name__ == "__main__":
    main()
