#!/usr/bin/env python3
"""Recalculate this authored fixture using CSV only; no model or database calls."""
import argparse
import csv
import hashlib
import json
from datetime import datetime, timezone
from pathlib import Path


def utc(value):
    parsed = datetime.fromisoformat(value.replace('Z', '+00:00'))
    if parsed.tzinfo is None or parsed.utcoffset().total_seconds() != 0:
        raise ValueError('Timestamp must explicitly use UTC: ' + value)
    return parsed.astimezone(timezone.utc)


def calculate(directory):
    names = ['orders.csv', 'order-items.csv', 'metric-contract.json']
    contract = json.loads((directory / names[2]).read_text())
    def rows(name, columns):
        with (directory / name).open(newline='') as source:
            reader = csv.DictReader(source)
            if reader.fieldnames != columns:
                raise ValueError('Unexpected columns: ' + name)
            result = list(reader)
            if any(None in row or any(row[c] is None for c in columns) for row in result):
                raise ValueError('Malformed CSV: ' + name)
            return result
    orders = rows(names[0], ['order_id', 'status', 'completed_at'])
    items = rows(names[1], ['order_id', 'item'])
    ids = [row['order_id'] for row in orders]
    if any(not value for value in ids) or len(ids) != len(set(ids)):
        raise ValueError('Missing or duplicate order_id')
    pairs = [(row['order_id'], row['item']) for row in items]
    if len(pairs) != len(set(pairs)) or any(not item or order not in ids for order,item in pairs):
        raise ValueError('Duplicate item, empty item, or orphan foreign key')
    if contract['timezone'] != 'UTC' or contract['counting_unit'] != 'distinct order_id' or contract['date_field'] != 'completed_at':
        raise ValueError('Unsupported metric contract')
    start, end = utc(contract['period_start_inclusive']), utc(contract['period_end_exclusive'])
    if start >= end:
        raise ValueError('Invalid interval')
    included, excluded = [], []
    for row in orders:
        stamp = utc(row['completed_at']) if row['completed_at'] else None
        reasons = []
        if row['status'] != contract['status']:
            reasons.append('status_not_completed')
        if stamp is None:
            if row['status'] == contract['status']:
                raise ValueError('Completed order has unresolved completed_at: ' + row['order_id'])
            reasons.append('completed_at_null')
        elif stamp < start:
            reasons.append('before_inclusive_start')
        elif stamp >= end:
            reasons.append('at_or_after_exclusive_end')
        if reasons:
            excluded.append({'order_id':row['order_id'], 'reasons':reasons})
        else:
            included.append(row['order_id'])
    joined = [row for row in items if row['order_id'] in included]
    result = {'included_order_ids':included, 'excluded_order_ids':[r['order_id'] for r in excluded], 'distinct_order_count':len(set(included)), 'joined_item_count':len(joined)}
    if result != contract['expected']:
        raise ValueError('Calculated result differs from authored expected contract: ' + json.dumps(result))
    return {'calculation':'Python standard-library CSV calculation', 'not_a_model_result':True, 'not_production_data':True, 'query_executed':False, 'input_sha256':{name:hashlib.sha256((directory/name).read_bytes()).hexdigest() for name in names}, 'source_order_rows':len(orders), 'source_item_rows':len(items), 'interval':{'start_inclusive':start.isoformat(),'end_exclusive':end.isoformat()}, **result, 'excluded_orders':excluded, 'included_joined_items':joined, 'checks':{'unique_order_ids':True,'unique_item_pairs':True,'foreign_keys_valid':True,'utc_timestamps_valid':True,'expected_contract_matches':True}, 'validation_passed':True}


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--source-dir', type=Path, default=Path(__file__).resolve().parent)
    parser.add_argument('--output', type=Path)
    args = parser.parse_args()
    receipt = json.dumps(calculate(args.source_dir), indent=2) + '\n'
    if args.output:
        args.output.write_text(receipt)
    else:
        print(receipt, end='')
