"""Run three fictional business workflows with Python 3. No accounts required."""

import argparse
import csv
from pathlib import Path


def billing():
    events = [('O-101', 60000, 60000, True), ('O-102', 55000, 55000, True),
              ('O-103', 48000, 51000, True), ('O-104', 22000, 22000, False),
              ('O-102', 55000, 55000, True)]
    seen = set()
    rows = []
    for order, contract, invoice, proof in events:
        if order in seen:
            continue
        seen.add(order)
        if not proof:
            owner, action = 'Operations', 'Get delivery proof'
        elif contract != invoice:
            owner, action = 'Commercial Ops', f'Resolve ${abs(invoice-contract):,} mismatch'
        else:
            owner, action = 'Finance', 'Review invoice draft'
        rows.append((order, contract, owner, action))
    return ('Order', 'Contracted USD', 'Owner', 'Next action'), rows


def inventory():
    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 = available / per_day if per_day > 0 else None
        if 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 = [('Bookings USD', 124000, 'bookings-export', 124000, 'CRM report'),
              ('Recognized revenue USD', 92000, 'closed-ledger', 88000, 'sales slide'),
              ('On-time delivery %', None, None, 96, 'operations slide')]
    rows = []
    for metric, trusted, source, reported, reported_source in claims:
        if trusted is None:
            result = 'Hold. Operations needs the delivery export.'
        elif trusted != reported:
            result = 'Escalate. Finance 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, reported_source, 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)))
