"""Extract the small, auditable ABS input snapshot used by income_demographics.

Usage: python extract_income_demographics.py SOURCE_DIRECTORY [--download]
Downloading is explicit; neither the model nor its tests use the network.
"""

import argparse
import hashlib
import json
from pathlib import Path
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
import zipfile

BASE = "https://www.abs.gov.au/statistics/economy/finance/household-income-and-wealth-australia/2019-20/"
FILES = {
    "composition": "9. Household composition.xlsx",
    "quintiles": "6. Gross household income.xlsx",
    "distribution": "1. Household income and income distribution, Australia.xlsx",
}
NS = {"m": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"}
PROFILES = [
    ("couple_children", "Couples with dependent children", "couple_children", "F", "G"),
    ("one_parent", "One-parent families with dependent children", "one_parent", "G", "H"),
    ("couple_under35", "Couples only, under 35", "couple_only", "H", "I"),
    ("couple_35_54", "Couples only, 35–54", "couple_only", "I", "J"),
    ("couple_55_64", "Couples only, 55–64", "couple_only", "J", "K"),
    ("couple_65plus", "Couples only, 65+", "couple_only", "K", "L"),
    ("other_family", "Other one-family households", "other_family", "O", "P"),
    ("multiple_family", "Multiple-family households", "multiple_family", "P", "Q"),
    ("single_under35", "Single adults, under 35", "single", "R", "S"),
    ("single_35_54", "Single adults, 35–54", "single", "S", "T"),
    ("single_55_64", "Single adults, 55–64", "single", "T", "U"),
    ("single_65plus", "Single adults, 65+", "single", "U", "V"),
    ("group", "Group households", "group", "W", "X"),
]


def sheet(path, number):
    with zipfile.ZipFile(path) as archive:
        strings = ["".join(node.itertext()) for node in
                   ET.fromstring(archive.read("xl/sharedStrings.xml"))]
        result = {}
        root = ET.fromstring(archive.read(f"xl/worksheets/sheet{number}.xml"))
        for cell in root.findall(".//m:c", NS):
            value = cell.find("m:v", NS)
            if value is not None:
                result[cell.get("r")] = (strings[int(value.text)]
                                         if cell.get("t") == "s" else float(value.text))
        return result


def extract(directory):
    paths = {key: directory / name for key, name in FILES.items()}
    income = sheet(paths["composition"], 2)
    demographics = sheet(paths["composition"], 4)
    qi = sheet(paths["quintiles"], 2)
    qd = sheet(paths["quintiles"], 4)
    distribution = sheet(paths["distribution"], 3)
    profiles = []
    for key, label, family, col, dcol in PROFILES:
        annual = lambda row: 52 * income[f"{col}{row}"]
        profiles.append({
            "id": key, "label": label, "family": family,
            "source_columns": {"Table 9.1": col, "Table 9.3": dcol},
            "households": 1000 * demographics[dcol + "59"],
            "persons": 1000 * demographics[dcol + "60"],
            "mean_private": annual(11), "mean_benefits": annual(12),
            "mean_gross": annual(13), "mean_disposable": annual(14),
            "median_private": annual(18), "median_gross": annual(20),
            "median_disposable": annual(21),
            "nonpositive_gross_share": demographics[dcol + "11"] / 100,
            "benefit_share_proportions": [demographics[f"{dcol}{r}"] / 100
                                           for r in range(26, 31)],
            "employment_proportions": [demographics[f"{dcol}{r}"] / 100
                                       for r in range(19, 23)],
            "mean_under18": demographics[dcol + "50"],
            "mean_age18_64": demographics[dcol + "51"],
            "mean_age65plus": demographics[dcol + "55"],
        })
    family_rows = dict(couple_children=45, one_parent=46, couple_only=47,
                       other_family=48, multiple_family=49, single=51, group=52)
    quintiles = []
    for i, (col, dcol) in enumerate(zip("BCDEF", "CDEFG")):
        quintiles.append({
            "quintile": i + 1, "households": 1000 * qd[dcol + "70"],
            "mean_private": 52 * qi[col + "10"],
            "mean_benefits": 52 * qi[col + "11"],
            "mean_gross": 52 * qi[col + "12"],
            "mean_disposable": 52 * qi[col + "13"],
            "family_proportions": {f: qd[f"{dcol}{row}"] / 100
                                   for f, row in family_rows.items()},
        })
    return {
        "year": "2019-20", "annualisation": "52 times published weekly amounts",
        "scope": "SIH private households; excludes very remote areas and non-private dwellings",
        "sources": {key: {"url": BASE + urllib.parse.quote(name),
                           "sha256": hashlib.sha256(paths[key].read_bytes()).hexdigest()}
                    for key, name in FILES.items()},
        "cell_map": {
            "Table 9.1": "means: rows 11–14; medians: 18,20,21",
            "Table 9.3": "nonpositive gross:11; employment:19–22; benefit reliance:26–30; ages:50,51,55; counts:59,60",
            "Table 6.1": "quintile means: rows 10–13, columns B–F",
            "Table 6.3": "quintile counts:70; family shares:45–49,51,52; columns C–G",
            "Table 1.2": "2019–20 column I; gross percentiles rows 17–25; Gini row 43",
        },
        "profiles": profiles, "quintiles": quintiles,
        "gross_deciles": [52 * distribution[f"I{r}"] for r in range(17, 26)],
        "gross_gini": distribution["I43"],
        "published_all_households": {
            "households": 1000 * demographics["Y59"],
            "persons": 1000 * demographics["Y60"],
            "mean_private": 52 * income["X11"], "mean_benefits": 52 * income["X12"],
            "mean_gross": 52 * income["X13"], "mean_disposable": 52 * income["X14"],
        },
        "notes": [
            "Gross income includes benefits; private income excludes them. Neither is equivalised income.",
            "Published means and counts are rounded and confidentialised independently; components need not add exactly.",
            "Government pensions and allowances in this survey include overseas pensions.",
            "Dependent children can be 18 or older; under-18 counts are recorded separately.",
            "Benefit reliance >=90% does not identify the zero-private-income share.",
        ],
        "external_comparison": {
            "source": "https://www.abs.gov.au/statistics/detailed-methodology-information/concepts-sources-methods/survey-income-and-housing-user-guide-australia/2019-20/comparison-australian-systems-national-accounts/income-comparison",
            "sih_australian_pensions_allowances_rounded": 110e9,
            "asna_pensions_allowances_adjusted_rounded": 132e9,
            "note": "ASNA excludes child care subsidy and private health rebate for this comparison. Remaining scope/measurement gap is not assigned to model households.",
        },
    }


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("source_directory", type=Path)
    parser.add_argument("--download", action="store_true")
    args = parser.parse_args()
    if args.download:
        args.source_directory.mkdir(parents=True, exist_ok=True)
        for name in FILES.values():
            urllib.request.urlretrieve(BASE + urllib.parse.quote(name), args.source_directory / name)
    output = Path(__file__).with_name("data") / "income-demographics-2019-20.json"
    output.write_text(json.dumps(extract(args.source_directory), indent=2) + "\n")
    print(output)
