#!/usr/bin/env python3
"""Offline hypothetical planning example, NOT IPHTML pricing or a revenue forecast.
Edit the named inputs below and run with Python 3. No network requests or packages.
Money is USD; traffic uses decimal MB/GB. Setup amortization is for planning only.
"""
from decimal import Decimal, ROUND_CEILING
import json


def estimate(skus=500, sites=2, regions=2, checks_per_day=4, days=30,
             attempts="1.25", mb_per_attempt="0.20", price_per_gb="5",
             useful_fraction="0.90", infra="60", maintenance_hours="8",
             engineering_hourly="50", review_hours="6", review_hourly="30",
             setup_hours="20", planning_months="6", contribution_per_order="30"):
    values = locals().copy()
    d = {k: Decimal(str(v)) for k, v in values.items()}
    if any(not v.is_finite() or v < 0 for v in d.values()):
        raise ValueError("Inputs must be finite and nonnegative")
    for key in ("skus", "sites", "regions", "checks_per_day", "days", "planning_months"):
        if d[key] <= 0 or d[key] != d[key].to_integral_value():
            raise ValueError(key + " must be a positive integer")
    if d["attempts"] < 1 or not 0 < d["useful_fraction"] <= 1:
        raise ValueError("Attempts must be >= 1 and useful_fraction in (0, 1]")
    n = d["skus"] * d["sites"] * d["regions"] * d["checks_per_day"] * d["days"]
    gb = n * d["attempts"] * d["mb_per_attempt"] / 1000
    proxy = gb * d["price_per_gb"]
    recurring = proxy + d["infra"] + d["maintenance_hours"] * d["engineering_hourly"] + d["review_hours"] * d["review_hourly"]
    setup = d["setup_hours"] * d["engineering_hourly"]
    monthly = recurring + setup / d["planning_months"]
    useful = n * d["useful_fraction"]
    def money(value):
        return str(value.quantize(Decimal("0.01")))
    def orders(cost):
        return int((cost / d["contribution_per_order"]).to_integral_value(rounding=ROUND_CEILING)) if d["contribution_per_order"] > 0 else None
    return {
        "planned_observations": int(n), "expected_useful_observations": format(useful.normalize(), 'f'),
        "traffic_gb_decimal": format(gb.normalize(), 'f'), "proxy_cost_usd": money(proxy),
        "recurring_monthly_usd": money(recurring), "setup_usd": money(setup),
        "monthly_with_setup_allocation_usd": money(monthly), "first_month_with_full_setup_usd": money(recurring + setup),
        "cost_per_1000_useful_usd": money(monthly / useful * 1000),
        "incremental_orders_monthly_break_even": orders(monthly),
        "incremental_orders_first_month_break_even": orders(recurring + setup),
    }


if __name__ == "__main__":
    print(json.dumps({
        "notice": "HYPOTHETICAL inputs; no provider benchmark, quotation or revenue forecast",
        "baseline": estimate(),
        "larger_responses_2mb": estimate(mb_per_attempt="2"),
        "more_retries_2_attempts": estimate(attempts="2"),
        "lower_useful_fraction_60pct": estimate(useful_fraction="0.60"),
    }, indent=2))
