"""Part three, analyses added after the results (not in the frozen protocol; labelled as such on the page).

1. Observed payback: payback read directly from what the analyst sees at the cutoff, the cumulative margin per account
   acquired, month by month from the cohorts old enough to have reached each month; none within the 24 observed months
   is reported as not reached yet.
2. Two sentences on the page, measured: how the true revenue per account acquired moves over its first 18 months against
   its first month (why ignoring churn lands near the true payback), and how many of the accounts that were active again
   after a first activity churn had cancelled and come back in between.
3. Sensitivity: the base scenario with the idle-month rate and the seat-add rate each halved and raised by half (both
   account types), the two rates that drive the ends of the churn range.

The same seeds and generator as the reported run; the protocol file is not changed. `python -B saas_added.py run` writes
results-saas-added.json; `check` re-draws and compares byte for byte. One VERDICT line each.
"""
from __future__ import annotations

import copy
import hashlib
import os
import sys
from pathlib import Path

import numpy as np

import saas_pipeline
from retail import subscription as sb

ROOT = Path(__file__).resolve().parent
OUT = ROOT / 'results-saas-added.json'
SCALES = [0.5, 1.5]
SENSITIVITY = {'idle_month': 'Idle-month rate', 'seat_add': 'Seat-add rate'}


def observed_payback(sim: dict, protocol: dict) -> dict:
    cutoff = protocol['calendar']['cutoff_month']
    margin = protocol['payback']['gross_margin']
    s = sim['signup']
    per_month = []
    for age in range(cutoff):
        old_enough = s <= cutoff - age
        per_month.append(float(sim['MRR'][old_enough, age].mean()) * margin)
    cum = np.cumsum(per_month)
    out = {}
    for cost in protocol['payback']['acquisition_cost_usd']['sweep']:
        hit = np.nonzero(cum >= cost - 1e-9)[0]
        out[str(cost)] = int(hit[0]) + 1 if len(hit) else None
    return out


def revenue_path(sim: dict) -> dict:
    """True revenue per account acquired in sign-up months 1 to 12 (lost accounts at zero), against its first month."""
    acquired = sim['signup'] <= 12
    per = sim['MRR'][acquired].mean(axis=0)
    return {'month_12_over_first': float(per[11] / per[0]), 'month_18_over_first': float(per[17] / per[0]),
            'first_18_mean_over_first': float(per[:18].mean() / per[0])}


def active_again_detail(sim: dict) -> dict:
    """Of accounts whose first activity churn fell in months 13 to 18 and that used the product again by month 24, the
    share that had cancelled and come back in between."""
    acm = sb.activity_churn_month(sim)
    early = (acm >= 13) & (acm <= 18)
    again = np.zeros(len(acm), dtype=bool)
    returned = np.zeros(len(acm), dtype=bool)
    for m in range(15, 25):
        again |= early & (m >= acm + 2) & sb.at_month(sim, sim['ACTIVE'], m, False)
        returned |= early & (m > acm) & sb.at_month(sim, sim['REACT'], m, False)
    return {'first_activity_churns': int(early.sum()), 'active_again': int(again.sum()),
            'active_again_after_cancel_and_return': float((again & returned).sum() / again.sum())}


def scaled(protocol: dict, rate: str, scale: float) -> dict:
    p = copy.deepcopy(protocol)
    pair = p['generator'][rate]
    pair['value'] *= scale
    pair['no_value'] *= scale
    return p


def compute(protocol: dict) -> dict:
    base = {}
    for scenario in protocol['scenarios']:
        seeds = []
        for seed in protocol['seeds']:
            _, sim = sb.measure(protocol, scenario, seed)
            seeds.append({'seed': seed, 'observed_payback': observed_payback(sim, protocol), 'revenue_path': revenue_path(sim),
                          'active_again': active_again_detail(sim)})
        body = [{k: v for k, v in s.items() if k != 'seed'} for s in seeds]
        base[scenario] = {'summary': saas_pipeline.summarize(saas_pipeline._round(body)), 'seeds': saas_pipeline._round(seeds)}
    cost = str(protocol['payback']['acquisition_cost_usd']['base'])
    sens = []
    for rate, label in SENSITIVITY.items():
        for scale in SCALES:
            p = scaled(protocol, rate, scale)
            rows = []
            for seed in protocol['seeds']:
                out, sim = sb.measure(p, protocol['base_scenario'], seed)
                rows.append({'churn': {k: out['churn'][k] for k in ('logo_cancel', 'logo_activity', 'revenue_gross', 'revenue_net', 'truth')},
                             'payback': {k: out['payback'][cost][k] for k in ('simple', 'logo_cancel', 'logo_activity', 'revenue_gross', 'revenue_net', 'truth')},
                             'observed_payback': observed_payback(sim, protocol)[cost],
                             'net_revenue_retention': out['expansion']['net_revenue_retention']})
            sens.append({'rate': rate, 'label': label, 'scale': scale,
                         'value': round(protocol['generator'][rate]['value'] * scale, 6),
                         'no_value': round(protocol['generator'][rate]['no_value'] * scale, 6),
                         'summary': saas_pipeline.summarize(saas_pipeline._round(rows))})
    return saas_pipeline._round({'schema': 'saas-added/1', 'added_after_results': True,
                                 'protocol_sha256': saas_pipeline.PROTOCOL_SHA256, 'base': base,
                                 'sensitivity': {'scenario': protocol['base_scenario'], 'acquisition_cost_usd': int(cost),
                                                 'runs': sens}})


def main(argv):
    cmd = argv[1] if len(argv) > 1 else ''
    protocol = saas_pipeline.require_pinned()
    body = saas_pipeline.text(compute(protocol))
    if cmd == 'run':
        tmp = OUT.with_suffix('.json.tmp')
        tmp.write_text(body, encoding='utf-8')
        os.replace(tmp, OUT)
        print(f'VERDICT: PASS (results-saas-added.json {len(body.encode())} bytes, sha256 {hashlib.sha256(body.encode()).hexdigest()})')
    elif cmd == 'check':
        same = OUT.read_text(encoding='utf-8') == body
        print('VERDICT: PASS (replay matches results-saas-added.json byte for byte)' if same
              else 'VERDICT: FAIL (replay differs from results-saas-added.json)')
        if not same:
            raise SystemExit(1)
    else:
        raise SystemExit('usage: saas_added.py run|check')


if __name__ == '__main__':
    main(sys.argv)
