#!/usr/bin/env python3
"""Reproduce dated public-quote arithmetic locally; no network or account access."""
from decimal import Decimal, ROUND_HALF_UP
from pathlib import Path
import json

ROOT = Path(__file__).resolve().parent

def money(value):
    if value is None:
        return None
    return format(Decimal(str(value)).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP), '.2f')

def calculate(inputs):
    rows = []
    for quote in inputs['quotes']:
        row = {key: quote[key] for key in ('provider', 'plan', 'subscribers', 'sourceId', 'available')}
        row['monthlyBillQuote'] = money(quote.get('monthlyBillQuote'))
        row['twelveMonthlyBillsArithmetic'] = money(Decimal(quote['monthlyBillQuote']) * 12) if quote.get('monthlyBillQuote') is not None else None
        row['publishedAnnualTotalQuote'] = money(quote.get('publishedAnnualTotalQuote'))
        row['monthlyEquivalentFromAnnualTotalArithmetic'] = money(Decimal(quote['publishedAnnualTotalQuote']) / 12) if quote.get('publishedAnnualTotalQuote') is not None else None
        row['annualBillingMonthlyDisplay'] = money(quote.get('annualBillingMonthlyDisplay'))
        row['annualTotalFromMonthlyDisplayArithmetic'] = money(Decimal(quote['annualBillingMonthlyDisplay']) * 12) if quote.get('annualBillingMonthlyDisplay') is not None else None
        row['standardAnnualTotalUnknown'] = quote['available'] and quote.get('publishedAnnualTotalQuote') is None
        row['firstYearPromoAnnualTotalQuote'] = money(quote.get('firstYearPromoAnnualTotalQuote'))
        row['firstYearPromoMonthlyEquivalentArithmetic'] = money(Decimal(quote['firstYearPromoAnnualTotalQuote']) / 12) if quote.get('firstYearPromoAnnualTotalQuote') is not None else None
        row['excludedFromTotals'] = ['payment processing', 'platform revenue share', 'add-ons', 'taxes', 'foreign exchange', 'unobserved discounts']
        rows.append(row)
    return {
        'schemaVersion': 'fewertools.newsletter-cost-model-results.v1',
        'sourceReadOn': inputs['sourceReadOn'],
        'execution': 'Local Python Decimal arithmetic only; no provider workflow or checkout executed',
        'currencyDisplay': inputs['currencyDisplay'],
        'currencyCode': inputs['currencyCode'],
        'currencyScope': inputs['currencyScope'],
        'rounding': 'Derived display values rounded to two decimals, half up; no rounded monthly display is inverted to invent an annual total',
        'scenarioCount': len(rows),
        'scenarios': rows,
    }

def render(inputs):
    return json.dumps(calculate(inputs), ensure_ascii=False, indent=2, sort_keys=True) + '\n'

if __name__ == '__main__':
    print(render(json.loads((ROOT / 'cost-inputs.json').read_text())), end='')
