"""Consolidated 2025 accounting check before comparing tax systems.

All amounts use the 2024-25 ASNA vintage and current Australian prices. July
2025 remains the policy date. This reconciles resources, income redistribution
and financing separately. It does not convert national income into taxable
household cash, allocate tax incidence, or recommend u/s.

Domestic income taxes and transfers cancel on consolidation. Taxes on products
are already included in the market-price valuation of national income/output.
Do not add either category to that resource total or remove GST from only one
system. Domestic government borrowing is a financing flow, not new national
income. Net borrowing from overseas is reconciled in the capital account.

Run: python3 national_reconciliation_2025.py --json /tmp/national-reconciliation-2025.json
No network, plots or document builds.
"""

import argparse
import json
from pathlib import Path

from population_comparison_2025 import government_accounts, load_controls

DATA = Path(__file__).with_name("data") / "national-reconciliation-2025.json"


def load_data():
    return json.loads(DATA.read_text())


def value(data, table, column):
    return data["tables"][table][column]["value"] * 1e6


def allocation_difference(*, resource_change=0.0, public_use_change=0.0,
                          other_use_change=0.0):
    """Required aggregate change in household consumption, in common prices.

    Other uses include any investment/saving/external resource use held outside
    the particular comparison. Redistribution among households cannot alter
    this sum. A financing change alone must not be passed as a resource change.
    """
    return resource_change - public_use_change - other_use_change


def match_resource_split(private_consumption, public_purchases, cash_support):
    """Static q=1 calibration in a single common purchasing-power unit.

    P=(1-u-s)R/(1-u), S=sR/(1-u), net UBI=uP. Thus u=B/P and
    s=(1-u)S/(P+S). Match NET UBI buying power, not gross taxed-back UBI.
    R includes the resources going to public purchases, not just household
    cash income after embedded taxes. No further GST conversion applies.
    """
    if not 0 <= cash_support < private_consumption or public_purchases < 0:
        raise ValueError("Require non-negative public purchases and 0 <= support < private consumption")
    resources = private_consumption + public_purchases
    u = cash_support / private_consumption
    s = (1-u)*public_purchases/resources
    gross_ubi = u*resources/(1-u)
    return {"u": u, "s": s, "total_rate": u+s,
            "resources": resources, "private_consumption": private_consumption,
            "public_purchases": public_purchases, "net_ubi_buying_power": (1-u-s)*gross_ubi,
            "gross_ubi_in_common_price_units": gross_ubi}


def indicative_rate_calibration():
    """Approximate public-purchases/cash-support match, not a plot calibration.

    Include general-government current consumption and investment. CCS and
    PHI rebates are services in this comparison but are included in ASNA cash
    social assistance; move their funding out of household-financed consumption
    into public purchases without increasing total resources. Cash support is
    before any recipient income tax, an approximation to its buying power.
    Government interest and other transfers are not classified as purchases.
    Additional publicly funded nonprofit services need a separate incidence
    allocation; this calculation is not a full inherited-budget replacement.
    """
    data, controls = load_data(), load_controls()
    r = reconcile(data)
    adjustments = controls["benefit_scope_adjustments"]
    provider_subsidies = 1e6*(adjustments["ccs_aud_million"]+
                             adjustments["private_health_rebate_aud_million"])
    private = r["resources"]["household_and_nonprofit_final_consumption"]-provider_subsidies
    public = (r["resources"]["general_government_final_consumption"]
              + value(data, "national_capital", "M")
              + controls["tables"]["capital"]["AS"]["2024-25"]*1e6
              + provider_subsidies)
    support = controls["tables"]["household"]["M"]["2024-25"]*1e6-provider_subsidies
    result = match_resource_split(private, public, support)
    result["status"] = "Indicative aggregate resource match; household incidence and plot income conversion are not calibrated"
    result["assumptions"] = [
        "Common Australian price units; q=1 applied to resources remaining for household consumption and general-government purchases.",
        "Private/public-corporation investment and the external balance remain outside this allocation and unchanged.",
        "Cash support is treated as spendable before recipient income-tax adjustments; rates are rounded accordingly.",
        "Public purchases include current consumption, gross capital formation, inventories and CCS/PHI service funding; not all government financial outlays.",
        "Do not insert these rates into existing equal-cash-income plots: allocating embedded tax incidence is still required.",
    ]
    return result


def reconcile(data=None):
    data = load_data() if data is None else data
    n = lambda c: value(data, "national_income", c)
    k = lambda c: value(data, "national_capital", c)
    h = lambda c: value(data, "household", c)
    g = lambda c: value(data, "government", c)
    government = government_accounts(load_controls())
    checks = {}

    def check(name, left, right, tolerance=4e6):
        residual = left-right
        if abs(residual) > tolerance:
            raise ValueError(f"{name}: accounting residual ${residual:,.0f}")
        checks[name] = {"left": left, "right": right, "rounding_residual": residual}

    check("national_primary_income", n("B")+n("C")+n("D")+n("E")+n("F"), n("G"))
    check("national_disposable_income", n("G")+n("H")+n("I"), n("J"))
    sectors = {"households_and_nonprofits": h("AJ"), "general_government": g("CW"),
               "nonfinancial_corporations": value(data, "nonfinancial", "AB"),
               "financial_corporations": value(data, "financial", "AA")}
    check("consolidated_sector_disposable_income", sum(sectors.values()), n("J"))
    check("national_resource_uses", n("K")+n("L")+n("R")+n("S"), n("J"))
    check("national_net_saving", n("N")+n("O")+n("P")+n("Q"), n("R"))
    check("household_disposable_income_uses", h("AK")+h("AL")+h("AM"), h("AJ"))
    check("personal_tax_cross_sector", h("AA"), government["individual_income_tax"])
    check("corporation_tax_cross_sector", value(data, "nonfinancial", "T")
          + value(data, "financial", "T"), government["corporation_income_tax"])
    check("national_capital_sources", k("F")+k("G")+k("H")-k("I"), k("J"))
    check("national_capital_uses", k("N")+k("R")+k("S")+k("T")+k("U"), k("J"))
    check("fixed_capital_by_sector", k("K")+k("L")+k("M"), k("N"))
    check("government_funding", government["receipts_excluding_depreciation"]
          + government["net_borrowing"], government["uses_excluding_depreciation"])

    taxes = government["production_import_taxes"] + g("CF") + g("CG")
    non_tax_receipts = g("CA") + g("CI")
    check("government_receipts", taxes+non_tax_receipts,
          government["receipts_excluding_depreciation"])
    spending = {
        "current_public_consumption_excluding_depreciation": government["direct_government_consumption_excluding_depreciation"],
        "investment_and_net_capital_transactions": government["investment_and_net_other_capital_uses"],
        "social_assistance_including_provider_subsidies": government["social_assistance_including_provider_subsidies"],
        "interest": government["government_interest"],
        "subsidies": government["government_subsidies"],
        "other_current_transfers": g("CS")+g("CT"),
    }
    check("government_uses_breakdown", sum(spending.values()), government["uses_excluding_depreciation"])
    net_income = n("J")-n("S")
    consumption = n("K")+n("L")
    check("net_income_allocation", consumption+n("R"), net_income)
    # A demonstration of consolidation, NOT a proposed tax abolition policy:
    # move receipts back to the paying sectors while retaining all other flows.
    personal, company = government["individual_income_tax"], government["corporation_income_tax"]
    before_income_tax_sectors = {
        "households_and_nonprofits": sectors["households_and_nonprofits"]+personal,
        "corporations_combined": sectors["nonfinancial_corporations"]+sectors["financial_corporations"]+company,
        "general_government": sectors["general_government"]-personal-company,
    }
    check("income_tax_reallocation_creates_no_resources", sum(before_income_tax_sectors.values()), sum(sectors.values()))
    return {
        "reference_date": "2025-07-01", "aggregate_year": "2024-25",
        "valuation": "Common 2024-25 Australian current prices, including existing product taxes; no extra GST adjustment",
        "resources": {
            "gross_national_disposable_income": n("J"),
            "capital_consumption": n("S"),
            "net_national_disposable_income": net_income,
            "net_national_saving": n("R"),
            "household_and_nonprofit_final_consumption": n("L"),
            "general_government_final_consumption": n("K"),
            "total_final_consumption": consumption,
            "net_product_and_production_taxes_already_in_income": n("E"),
        },
        "sector_disposable_incomes": sectors,
        "income_tax_reallocation_example": before_income_tax_sectors,
        "government_financing": {"taxes": taxes, "non_tax_receipts": non_tax_receipts,
                                  "net_borrowing": government["net_borrowing"],
                                  "total_uses": government["uses_excluding_depreciation"]},
        "government_uses": spending,
        "national_capital_account": {
            "gross_saving_and_net_capital_transfers": k("J"),
            "fixed_capital_formation": k("N"), "inventories": k("R"),
            "net_nonproduced_asset_acquisition": k("S"), "statistical_discrepancy": k("T"),
            "net_borrowing_from_overseas": -k("U"),
            "general_government_net_borrowing": government["net_borrowing"],
            "other_domestic_sectors_net_lending": government["net_borrowing"]+k("U"),
        },
        "checks": checks,
        "comparison_constraints": {
            "equal_resources_public_and_other_uses_implies_household_consumption_change": allocation_difference(),
            "one_billion_more_public_use_at_fixed_resources_reduces_household_consumption_by": -allocation_difference(public_use_change=1e9),
            "rule": "Sum of household gains minus losses equals change in resources minus change in public use minus change in other uses, all in common prices.",
        },
        "application": [
            "Start from consolidated resources, not household cash income after embedded taxes.",
            "Corporation and personal income taxes redistribute this total; adding them to it would double-count income.",
            "Company earnings include distributions and retained income. Allocating them to owners must not count dividends, franking credits or superannuation income twice.",
            "Government interest, benefits and subsidies are transfers, not additional real output. They must be reconciled with recipient income, including foreign recipients.",
            "Public consumption and public investment remain separate. The remainder of government spending after welfare is not a services measure.",
            "Government borrowing is not household income or new national resources. Overseas financing enters the national capital account explicitly.",
            "National income/consumption includes non-cash items. These totals establish the resource constraint, not the VoTa cash tax base or an annual UBI amount.",
            "Allocate embedded taxes across households before using July 2025 cash-income scenarios to rank winners and losers.",
        ],
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--json", type=Path)
    args = parser.parse_args()
    result = reconcile()
    if args.json:
        args.json.write_text(json.dumps(result, indent=2)+"\n")
    print("July 2025 comparison: consolidated 2024-25 resource and financing accounts")
    for name, amount in result["resources"].items():
        print(f"{name}: ${amount/1e9:,.1f} billion")
    print(f"Accounting checks passed: {len(result['checks'])}")
    print("Equal total resources, public use and other uses require equal aggregate household consumption.")
    print("No UBI amount or household ranking is inferred from these national-account totals.")


if __name__ == "__main__":
    main()
