import csv
import json
from pathlib import Path

def analyze(rows):
    unique = {}
    excluded = []
    for line, row in enumerate(rows, start=2):
        key = row["order_id"]
        if key in unique:
            if row != unique[key]:
                raise ValueError(f"Conflicting order_id: {key}")
            excluded.append({"csv_line": line, "order_id": key, "reason": "duplicate"})
        else:
            unique[key] = row
    included = []
    for row in unique.values():
        if row["status"] != "paid":
            excluded.append({"order_id": row["order_id"], "reason": row["status"]})
        elif row["amount_rub"] == "":
            excluded.append({"order_id": row["order_id"], "reason": "missing_amount"})
        else:
            included.append({**row, "amount_rub": int(row["amount_rub"])})
    summary = []
    for channel in sorted({r["channel"] for r in included}):
        group = [r for r in included if r["channel"] == channel]
        total = sum(r["amount_rub"] for r in group)
        summary.append({"channel": channel, "count": len(group), "total_rub": total,
                        "average_rub": total / len(group)})
    total = sum(r["amount_rub"] for r in included)
    return {"count": len(included), "total_rub": total,
            "average_rub": total / len(included) if included else None,
            "summary": summary, "included": included, "excluded": excluded}

if __name__ == "__main__":
    with Path(__file__).with_name("sales-demo.csv").open(newline="", encoding="utf-8-sig") as f:
        print(json.dumps(analyze(list(csv.DictReader(f))), ensure_ascii=False, indent=2))
