"""Deterministic synthetic economic sensitivity evaluation; not a performance test.
Run: python3 accepted_work_sensitivity.py --out OUTPUT_DIRECTORY
Stdlib only. Monetary inputs are hypothetical USD; no vendor/customer data.
"""
import argparse
import csv
import hashlib
import itertools
import json
from datetime import datetime, timezone
from pathlib import Path

INPUTS = {
    'baseline_preparer_minutes': 30, 'baseline_reviewer_minutes': 10,
    'assisted_preparer_minutes': 8, 'preparer_cost_per_hour': 45,
    'reviewer_cost_per_hour': 120, 'contribution_per_redeployable_hour': 80,
    'review_minutes': [5, 15, 30], 'rework_preparer_minutes_per_case': [0, 10, 30],
    'accepted_cases_per_month': [50, 200, 500], 'recurring_cost_usd': [250, 750, 1500],
    'realization_fraction': [0, 0.25, 0.5, 1], 'implementation_usd': [3000, 12000],
}

def evaluate(n, review, rework, recurring, realization, implementation):
    hp = n * (30 - 8 - rework) / 60
    hr = n * (10 - review) / 60
    positive_value = max(hp, 0) * 45 + max(hr, 0) * 120
    extra_cost = max(-hp, 0) * 45 + max(-hr, 0) * 120
    capacity = hp + hr
    # Cash avoidance and redeployment are ALTERNATIVE scenarios, never added.
    cash_net = positive_value * realization - extra_cost - recurring
    # Different roles are not assumed interchangeable: new work is bounded by
    # net preparer hours AND sufficient reviewer capacity. If reviewer capacity
    # falls, redeployment is held at zero, not optimistically borrowed.
    eligible_hours = max(hp, 0) if hr >= 0 else 0
    redeploy_net = eligible_hours * realization * 80 - extra_cost - recurring
    proxy = positive_value - extra_cost - recurring
    return dict(cases=n, review_minutes=review, rework_minutes=rework,
                recurring_usd=recurring, realization=realization, implementation_usd=implementation,
                preparer_hours_delta=round(hp, 6), reviewer_hours_delta=round(hr, 6),
                net_capacity_hours=round(capacity, 6), labor_value_proxy_net=round(proxy, 2),
                cash_avoidance_net=round(cash_net, 2), redeployment_net=round(redeploy_net, 2),
                cash_payback_months=round(implementation/cash_net, 6) if cash_net > 0 else None,
                redeployment_payback_months=round(implementation/redeploy_net, 6) if redeploy_net > 0 else None)

def main():
    p = argparse.ArgumentParser(); p.add_argument('--out', type=Path, required=True)
    args = p.parse_args(); args.out.mkdir(parents=True, exist_ok=True)
    rows = [evaluate(*v) for v in itertools.product(INPUTS['accepted_cases_per_month'], INPUTS['review_minutes'],
            INPUTS['rework_preparer_minutes_per_case'], INPUTS['recurring_cost_usd'],
            INPUTS['realization_fraction'], INPUTS['implementation_usd'])]
    with (args.out/'scenarios.csv').open('w', newline='') as f:
        w=csv.DictWriter(f, fieldnames=rows[0].keys()); w.writeheader(); w.writerows(rows)
    selected = {name:evaluate(*values) for name, values in {
        'reference':(200,5,10,750,.5,12000),
        'no_realization':(200,5,10,750,0,12000),
        'review_bottleneck':(200,15,10,750,.5,12000),
        'heavy_rework':(200,5,30,750,.5,12000),
        'high_recurring_cost':(200,5,10,1500,.5,12000),
        'small_volume':(50,5,10,750,.5,12000),
    }.items()}
    summary = {'executed_utc':datetime.now(timezone.utc).isoformat(), 'scenario_count':len(rows),
        'inputs':INPUTS, 'selected_scenarios':selected,
        'cash_positive':sum(r['cash_avoidance_net']>0 for r in rows),
        'cash_nonpositive':sum(r['cash_avoidance_net']<=0 for r in rows),
        'redeployment_positive':sum(r['redeployment_net']>0 for r in rows),
        'redeployment_nonpositive':sum(r['redeployment_net']<=0 for r in rows),
        'cash_net_range':[min(r['cash_avoidance_net'] for r in rows),max(r['cash_avoidance_net'] for r in rows)],
        'limitations':'Designed grid, not a sample: counts are not probabilities. No AI, accounting workflow or customer performance tested. All effort, volume, costs and realization inputs are assumptions. Constant steady state, no ramp, discount, inflation, tax or failure loss. Quality equivalence is assumed, not demonstrated. Negative role deltas are charged in full even at zero realization; positive savings require realization. Redeployment disallowed if reviewer delta is negative. Payback is simple undiscounted months and undefined at nonpositive benefit.',
        'script_sha256':hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
        'csv_sha256':hashlib.sha256((args.out/'scenarios.csv').read_bytes()).hexdigest()}
    (args.out/'results.json').write_text(json.dumps(summary,indent=2)+'\n')
    print(json.dumps(summary,indent=2))

if __name__ == '__main__': main()
