"""Run three business workflow examples with Python 3."""

import argparse
import csv
from pathlib import Path


def billing(events=None):
    # Order, shipment, event, agreed amount, proposed amount, proof reference.
    if events is None:
        events = [('O-101', 'S-1', 'E-1', 60000, 60000, 'P-1'),
                  ('O-102', 'S-1', 'E-2', 55000, 55000, 'P-2'),
                  ('O-103', 'S-1', 'E-3', 48000, 51000, 'P-3'),
                  ('O-104', 'S-1', 'E-4', 22000, 22000, ''),
                  ('O-102', 'S-1', 'E-2', 55000, 55000, 'P-2')]
    shipments = {}
    event_shipments = {}
    rows = {}
    for order, shipment, event, contract, invoice, proof in events:
        key = (order, shipment)
        details = (contract, invoice, proof)
        earlier_key = event_shipments.setdefault(event, key)
        if earlier_key != key:
            action = ('Operations', 'Hold. Event ID points to multiple shipments.')
            rows[earlier_key] = (*rows[earlier_key][:-2], *action)
        elif key in shipments:
            if shipments[key] == details:
                continue
            action = ('Finance and Operations', 'Hold. Review changed shipment details.')
        elif not proof:
            action = ('Operations', 'Get delivery proof')
        elif contract != invoice:
            action = ('Commercial Ops', f'Resolve ${abs(invoice-contract):,} mismatch')
        else:
            action = ('Finance', 'Review invoice draft')
        shipments.setdefault(key, details)
        rows[key] = (order, contract, *action)
    return ('Order', 'Contracted USD', 'Owner', 'Next action'), list(rows.values())


def inventory(items=None):
    if items is None:
        items = [('A-42', 120, 30, 40, 5), ('B-19', 150, 10, 20, 5),
                 ('C-08', 20, 0, 10, None)]
    rows = []
    for sku, on_hand, reserved, per_day, eta in items:
        available = on_hand - reserved
        cover = max(0, available) / per_day if per_day > 0 else None
        if available <= 0:
            action = 'Review stock now'
        elif cover is None:
            action = 'Review demand before forecasting'
        elif eta is None:
            action = 'Confirm supplier ETA'
        elif cover <= eta:
            action = 'Buyer reviews transfer or expedite'
        else:
            action = 'Monitor'
        rows.append((sku, available, per_day, f'{cover:g}' if cover is not None else 'Unknown',
                     eta if eta is not None else 'Unknown', action))
    return ('SKU', 'Available units', 'Daily demand', 'Days of cover', 'Receipt ETA in days', 'Next action'), rows


def review(claims=None):
    # Match period, definition and unit before comparing values.
    if claims is None:
        bookings = ('2026-10', 'Bookings', 'USD')
        revenue = ('2026-10', 'Recognized revenue', 'USD')
        delivery = ('2026-10', 'On-time delivery', '%')
        claims = [('Bookings USD', 124000, 'bookings-export', 124000, 'CRM report', bookings, bookings, 'Finance'),
                  ('Recognized revenue USD', 92000, 'closed-ledger', 88000, 'sales slide', revenue, revenue, 'Finance'),
                  ('On-time delivery %', None, None, 96, 'operations slide', None, delivery, 'Operations')]
    rows = []
    for metric, trusted, source, reported, reported_source, trusted_scope, reported_scope, owner in claims:
        if trusted is None or not source:
            result = 'Hold. Operations needs the delivery export.' if metric == 'On-time delivery %' else f'Hold. {owner} needs the source export.'
        elif (reported is None or not reported_source or not trusted_scope or not reported_scope
              or not all(trusted_scope) or not all(reported_scope)):
            result = f'Hold. {owner} needs complete evidence for both figures.'
        elif trusted_scope != reported_scope:
            result = f'Hold. {owner} checks the period, definition and unit.'
        elif trusted != reported:
            result = f'Escalate. {owner} validates the period and definition.'
        else:
            result = 'Include with source reference.'
        rows.append((metric, trusted if trusted is not None else 'Unknown', source or 'Missing',
                     reported if reported is not None else 'Unknown', reported_source or 'Missing', result))
    return ('Metric', 'System value', 'System source', 'Slide value', 'Slide source', 'Decision'), rows


if __name__ == '__main__':
    workflows = {'billing': billing, 'inventory': inventory, 'review': review}
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('workflow', choices=workflows)
    parser.add_argument('--output', type=Path)
    args = parser.parse_args()
    headers, records = workflows[args.workflow]()
    if args.output:
        with args.output.open('w', newline='', encoding='utf-8') as file:
            writer = csv.writer(file)
            writer.writerow(headers)
            writer.writerows(records)
    print(' | '.join(headers))
    for record in records:
        print(' | '.join(map(str, record)))
