"""Convert a quoted British price into purchasing power and weeks of gross weekly earnings."""
import argparse
import csv
from decimal import Decimal, InvalidOperation
from pathlib import Path


def amount(text):
    try:
        number = Decimal(text)
    except InvalidOperation:
        raise argparse.ArgumentTypeError("Use a decimal number")
    if not number.is_finite() or number < 0:
        raise argparse.ArgumentTypeError("Use a finite non-negative amount")
    return number


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("period", help="Price period, e.g. 1965")
    parser.add_argument("--target", default="2025", help="Price basis, default 2025; 2026-09 also available")
    prices = parser.add_mutually_exclusive_group(required=True)
    prices.add_argument("--pounds", type=amount, help="Decimal pounds at the time of the quote")
    prices.add_argument("--lsd", type=amount, nargs=3, metavar=("POUNDS", "SHILLINGS", "OLD_PENCE"))
    prices.add_argument("--guineas", type=amount, help="Guineas at 21 shillings each")
    args = parser.parse_args()

    with Path(__file__).with_name("indicators.csv").open() as stream:
        data = {row["period"]: row for row in csv.DictReader(stream)}
    if args.period not in data or args.target not in data:
        parser.error("Coverage is calendar years 1949–2025 and the month 2026-09")
    if args.lsd:
        pounds, shillings, old_pence = args.lsd
        if pounds % 1 or shillings % 1 or shillings >= 20 or old_pence >= 12:
            parser.error("Use whole pounds, 0–19 whole shillings and fewer than 12 old pence")
        nominal = pounds + shillings / 20 + old_pence / 240
    elif args.guineas is not None:
        nominal = args.guineas * Decimal("1.05")
    else:
        nominal = args.pounds
    quoted, target = data[args.period], data[args.target]
    print(f"{args.period} nominal quote: £{nominal:.4f}")
    for index, label in [("cpi_2015_100", "CPI"), ("rpi_jan1974_100", "RPI")]:
        multiplier = Decimal(target[index]) / Decimal(quoted[index])
        print(f"{args.target} purchasing power ({label}): £{nominal * multiplier:.2f} (×{multiplier:.3f})")
    weeks = nominal / Decimal(quoted["gb_weekly_gbp"])
    print(f"Gross earnings, GB whole-economy benchmark: {weeks:.3f} weeks ({quoted['weekly_source']})")
    print(f"Same weeks of {args.target} gross mean pay: £{weeks * Decimal(target['gb_weekly_gbp']):.2f}")
    for group, column in [("men", "manual_men_gbp"), ("women", "manual_women_gbp")]:
        if quoted[column]:
            print(f"Gross earnings, adult full-time manual {group}: {nominal / Decimal(quoted[column]):.3f} weeks")


if __name__ == "__main__":
    main()
