#!/usr/bin/env python3
import argparse
import csv
import json
from pathlib import Path

ORDER_HEADER = ['sync_date','order_date','order_id','merchant','fulfillment_type','order_total','item_subtotal','adjustment_total','reconciliation_delta']
ITEM_HEADER = ['sync_date','order_date','order_id','merchant','item_name','quantity','unit_price','item_total']


def load_rows(path, header):
    rows = []
    if not path.exists():
        return rows
    with path.open('r', encoding='utf-8', newline='') as fh:
        reader = csv.DictReader(fh)
        for row in reader:
            rows.append({k: row.get(k, '') for k in header})
    return rows


def write_rows(path, header, rows):
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open('w', encoding='utf-8', newline='') as fh:
        writer = csv.DictWriter(fh, fieldnames=header)
        writer.writeheader()
        writer.writerows(rows)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--input-json', required=True)
    parser.add_argument('--orders-csv', required=True)
    parser.add_argument('--items-csv', required=True)
    parser.add_argument('--merchant', required=True)
    parser.add_argument('--sync-date', required=True)
    args = parser.parse_args()

    payload = json.loads(Path(args.input_json).read_text(encoding='utf-8'))
    orders_path = Path(args.orders_csv)
    items_path = Path(args.items_csv)

    order_rows = load_rows(orders_path, ORDER_HEADER)
    item_rows = load_rows(items_path, ITEM_HEADER)

    seen_orders = {row['order_id'] for row in order_rows}
    seen_items = {(row['order_id'], row['item_name']) for row in item_rows}

    for order in payload.get('orders', []):
        if order['order_id'] not in seen_orders:
            order_rows.append({
                'sync_date': args.sync_date,
                'order_date': order.get('order_date', ''),
                'order_id': order['order_id'],
                'merchant': order.get('merchant', args.merchant),
                'fulfillment_type': order.get('fulfillment_type', ''),
                'order_total': order.get('order_total', ''),
                'item_subtotal': order.get('item_subtotal', ''),
                'adjustment_total': order.get('adjustment_total', ''),
                'reconciliation_delta': order.get('reconciliation_delta', ''),
            })
            seen_orders.add(order['order_id'])

        for item in order.get('items', []):
            key = (order['order_id'], item.get('item_name', ''))
            if key in seen_items:
                continue
            item_rows.append({
                'sync_date': args.sync_date,
                'order_date': order.get('order_date', ''),
                'order_id': order['order_id'],
                'merchant': order.get('merchant', args.merchant),
                'item_name': item.get('item_name', ''),
                'quantity': item.get('quantity', ''),
                'unit_price': item.get('unit_price', ''),
                'item_total': item.get('item_total', ''),
            })
            seen_items.add(key)

    write_rows(orders_path, ORDER_HEADER, order_rows)
    write_rows(items_path, ITEM_HEADER, item_rows)

    print(json.dumps({
        'orders_csv': str(orders_path),
        'items_csv': str(items_path),
        'orders_rows': len(order_rows),
        'items_rows': len(item_rows)
    }))


if __name__ == '__main__':
    main()
