"""Recalculate the fictional ECRS exercise using Python's standard library."""
from pathlib import Path
from datetime import datetime
from collections import Counter
import csv
import hashlib
import json

HERE = Path(__file__).resolve().parent
source = HERE / 'process-log.csv'
effort_fields = ['entry_minutes', 'copy_minutes', 'review_minutes',
                 'handoff_minutes', 'rework_minutes']
with source.open(newline='', encoding='utf-8') as handle:
    rows = list(csv.DictReader(handle))
assert rows, 'No request records'
assert len({r['request_id'] for r in rows}) == len(rows), 'Duplicate request ID'
totals = Counter()
for row in rows:
    values = {key: int(row[key]) for key in effort_fields + ['wait_minutes']}
    assert all(v >= 0 for v in values.values()), 'Negative duration'
    received, queued, reviewed, handed_off = [datetime.fromisoformat(row[key])
        for key in ['received_at', 'queued_at', 'review_started_at', 'handoff_at']]
    assert all(t.utcoffset().total_seconds() == 28800
               for t in [received, queued, reviewed, handed_off]), 'Expected UTC+08:00'
    assert received <= queued <= reviewed <= handed_off, 'Timestamp order'
    before = (queued - received).total_seconds() / 60
    waiting = (reviewed - queued).total_seconds() / 60
    after = (handed_off - reviewed).total_seconds() / 60
    assert before == values['entry_minutes'] + values['copy_minutes']
    assert waiting == values['wait_minutes']
    assert after == sum(values[k] for k in effort_fields[2:])
    active = sum(values[k] for k in effort_fields)
    elapsed = (handed_off - received).total_seconds() / 60
    assert elapsed == active + waiting, 'Serial-process assumption does not hold'
    assert row['approved_before_handoff'] == 'true', 'Missing required approval'
    totals.update(values)
    totals.update(active_staff_minutes=active, lead_time_minutes=int(elapsed),
                  requests_with_rework=int(values['rework_minutes'] > 0))

count = len(rows)
summary = {
    'nature': 'fictional-teaching-exercise',
    'period': '2026-10-01/2026-10-04',
    'timezone': 'Asia/Shanghai',
    'source_file': source.name,
    'source_sha256': hashlib.sha256(source.read_bytes()).hexdigest(),
    'requests': count,
    'definitions': {
        'active': 'Staff-minutes; five effort categories, including rework once.',
        'waiting': 'Request-minutes between queue entry and review start; not staff effort.',
        'lead_time': 'Elapsed minutes from request receipt to handoff notification.',
        'assumption': 'Within each request: sequential work, one person at a time, one queue interval, no other waits.',
        'scope': 'Completed routine requests only. No incomplete, complex, or overnight requests. Not a representative sample.',
        'rework': 'Complete missing fields and check again after initial review; no additional wait in this exercise.',
    },
    'totals': dict(sorted(totals.items())),
    'means': {k: v / count for k, v in sorted(totals.items())
              if k != 'requests_with_rework'},
    'waiting_share_of_lead_time': totals['wait_minutes'] / totals['lead_time_minutes'],
    'copy_removal_scenario': {
        'status': 'conditional-estimate-not-measured',
        'assumption': 'Remove copying for all requests with zero added effort; waiting and other work unchanged.',
        'avoided_staff_minutes': totals['copy_minutes'],
        'avoided_staff_hours': totals['copy_minutes'] / 60,
        'remaining_active_staff_minutes': totals['active_staff_minutes'] - totals['copy_minutes'],
        'mean_active_staff_minutes': (totals['active_staff_minutes'] - totals['copy_minutes']) / count,
        'share_of_baseline_active_effort': totals['copy_minutes'] / totals['active_staff_minutes'],
        'measured_post_change_result': None,
    },
}
print(json.dumps(summary, indent=2, ensure_ascii=False))
