"""Audit fictional workshop bookings. Python 3, standard library only.
Usage: python audit_bookings.py bookings.csv
Reads the original file; prints JSON; does not rewrite records or call a service.
"""
import csv
import json
import sys
from decimal import Decimal, InvalidOperation


def audit(filename):
    accepted, issues, seen = [], [], set()
    with open(filename, encoding="utf-8-sig", newline="") as stream:
        reader = csv.DictReader(stream)
        if reader.fieldnames != ["booking_id", "topic", "seats", "unit_price"]:
            raise ValueError("Expected header: booking_id,topic,seats,unit_price")
        for number, row in enumerate(reader, start=1):
            reason = None
            booking_id = (row.get("booking_id") or "").strip()
            topic = (row.get("topic") or "").strip()
            if None in row or any(value is None for value in row.values()):
                reason = "wrong column count"
            elif not booking_id:
                reason = "missing booking_id"
            elif booking_id in seen:
                reason = "duplicate booking_id"
            # The first occurrence reserves an ID, even if another field is invalid.
            if booking_id:
                seen.add(booking_id)
            if reason is None and not topic:
                reason = "missing topic"
            if reason is None:
                try:
                    seats = int(row["seats"])
                    if str(seats) != row["seats"].strip() or seats <= 0:
                        raise ValueError
                except ValueError:
                    reason = "seats must be a positive whole number"
            if reason is None:
                try:
                    price = Decimal(row["unit_price"])
                    if not price.is_finite() or price < 0 or price.as_tuple().exponent < -2:
                        raise InvalidOperation
                except InvalidOperation:
                    reason = "unit_price must be a nonnegative amount with at most two decimals"
            if reason:
                issues.append({"record": number, "booking_id": booking_id, "reason": reason})
            else:
                accepted.append({"booking_id": booking_id, "topic": topic, "seats": seats, "price": price})
    total = sum((row["seats"] * row["price"] for row in accepted), Decimal("0"))
    return {"accepted_ids": [row["booking_id"] for row in accepted],
            "accepted_records": len(accepted), "rejected_records": len(issues),
            "seats": sum(row["seats"] for row in accepted),
            "booking_value": format(total, ".2f"), "issues": issues}


if __name__ == "__main__":
    if len(sys.argv) != 2:
        raise SystemExit("Usage: python audit_bookings.py bookings.csv")
    print(json.dumps(audit(sys.argv[1]), indent=2))
