#!/usr/bin/env python3
"""
Record a follow-up notice (or the reply that followed it) in data/audit/deployment_log.json, then recompute the analysis.

  .venv-analysis/bin/python -I scripts/log_followup.py sent  --state NC --district "Wake County Public School System" --date 2026-12-07 --source "campaign mailbox, sent folder"
  .venv-analysis/bin/python -I scripts/log_followup.py reply --state NC --district "Wake County Public School System" --date 2026-12-09 --class unclear --source "campaign mailbox, inbox"

Add --dry-run to validate without writing. Never put an email address or a person's name in --source.
"""
import argparse, json, subprocess, sys
from datetime import date
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]


def main():
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('action', choices=['sent', 'reply'])
    ap.add_argument('--state', required=True)
    ap.add_argument('--district', required=True)
    ap.add_argument('--date', required=True, help='YYYY-MM-DD, not in the future')
    ap.add_argument('--source', required=True, help='where the fact can be checked')
    ap.add_argument('--class', dest='reply_class', choices=['none', 'partial', 'unclear'])
    ap.add_argument('--log', default=str(ROOT / 'data/audit/deployment_log.json'))
    ap.add_argument('--dry-run', action='store_true')
    ap.add_argument('--no-recompute', action='store_true')
    a = ap.parse_args()

    def die(msg):
        sys.exit('refused: ' + msg)

    day = date.fromisoformat(a.date)
    if day > date.today():
        die('the date is in the future; log only what has happened')
    if '@' in a.source or not a.source.strip():
        die('--source must be non-empty and must not contain an email address')
    log = json.load(open(a.log))
    notices = log['model1_followup_wave']['notices']
    hit = next((n for n in notices if (n['district'], n['state']) == (a.district, a.state)), None)
    if a.action == 'sent':
        if hit:
            die('a notice for this district is already logged')
        sched = json.load(open(ROOT / 'data/analysis/rolling_horizon_schedule.json'))
        planned = {(x['district'], x['state']) for h in sched['horizons'].values() for w in h['waves'] for x in w['assignments']}
        planned |= {(x['district'], x['state']) for x in json.load(open(ROOT / 'data/analysis/deployment_impact.json'))['model1_followup_wave']['portfolio']}
        if (a.district, a.state) not in planned:
            die('the district is not in any computed plan (check the exact name and state)')
        notices.append({'district': a.district, 'state': a.state, 'sent_date': a.date, 'source': a.source})
    else:
        if not hit:
            die('no notice is logged for this district')
        if not a.reply_class:
            die('--class is required for a reply')
        if hit.get('reply_date_after_notice'):
            die('a reply is already logged')
        if day < date.fromisoformat(hit['sent_date']):
            die('the reply is dated before the notice')
        hit.update({'reply_date_after_notice': a.date, 'reply_class': a.reply_class, 'reply_source': a.source})
    log['updated'] = date.today().isoformat()
    n = len(notices)
    log['model1_followup_wave']['status'] = f'{n} follow-up notice{"s" if n != 1 else ""} logged.'
    if a.dry_run:
        print('valid; nothing written (dry run)')
        return
    Path(a.log).write_text(json.dumps(log, indent=2, ensure_ascii=False) + '\n')
    print('logged in', a.log)
    if not a.no_recompute:
        if Path(a.log).resolve() != (ROOT / 'data/audit/deployment_log.json').resolve():
            die('recompute only runs on the real log; use --no-recompute with another file')
        subprocess.run([sys.executable, '-I', str(ROOT / 'scripts/run_analysis.py')], check=True, cwd=ROOT)
        w = json.load(open(ROOT / 'data/analysis/deployment_impact.json'))['model1_followup_wave']
        print(f"notices {w['notices_sent']}, replies {w['converted_silent_to_replied']}, realized narrowing {w['realized_width_reduction_pts']:.3f} points")


if __name__ == '__main__':
    main()
