#!/usr/bin/env python3
"""Educational capacity calculation, stdlib only. Not a shift scheduler."""
import csv
from fractions import Fraction
from pathlib import Path

def need(orders, minutes_per_order, interval_minutes, productive_minutes):
    if isinstance(orders, bool) or int(orders) != orders or orders < 0:
        raise ValueError('orders must be a non-negative integer')
    norm, interval, productive = map(lambda x: Fraction(str(x)),
                                     (minutes_per_order, interval_minutes, productive_minutes))
    if norm <= 0 or interval <= 0 or not 0 < productive <= interval:
        raise ValueError('invalid norm, interval or productive minutes')
    work = orders * norm
    ratio = work / productive
    people = -(-ratio.numerator // ratio.denominator)
    return people, work, people * productive - work

def calculate(path):
    result = []
    seen = set()
    for row in csv.DictReader(Path(path).open(encoding='utf-8', newline='')):
        label = row['interval']
        if label in seen:
            raise ValueError('duplicate interval')
        seen.add(label)
        people, work, spare = need(int(row['orders']), row['minutes_per_order'],
                                  row['interval_minutes'], row['productive_minutes_per_person'])
        result.append({**row, 'work_minutes': str(work), 'people': people,
                       'spare_productive_minutes': str(spare)})
    if not result:
        raise ValueError('empty input')
    return result

if __name__ == '__main__':
    root = Path(__file__).resolve().parent
    rows = calculate(root / 'input.csv')
    with (root / 'workload-to-staff.csv').open('w', encoding='utf-8', newline='') as out:
        writer = csv.DictWriter(out, fieldnames=list(rows[0])); writer.writeheader(); writer.writerows(rows)
    for r in rows:
        print(r['interval'], 'orders', r['orders'], 'work', r['work_minutes'], 'people', r['people'])
