import csv, json
from pathlib import Path
root = Path(__file__).resolve().parent
with (root / "practice-sales.csv").open(encoding="utf-8-sig",newline="") as f:
    rows = list(csv.DictReader(f))
seen = set(); excluded = {"duplicate":0,"outside_period":0,"cancelled":0,"missing_amount":0}
totals = {}; valid_count = 0
for row in rows:
    key = row["order_id"]
    if key in seen:
        excluded["duplicate"] += 1; continue
    seen.add(key)
    if not "2026-10-01" <= row["date"] <= "2026-10-31":
        excluded["outside_period"] += 1; continue
    if row["status"] == "cancelled":
        excluded["cancelled"] += 1; continue
    if row["amount_yen"] == "":
        excluded["missing_amount"] += 1; continue
    amount = int(row["amount_yen"])
    valid_count += 1
    totals[row["department"]] = totals.get(row["department"],0) + amount
result = {"rows":len(rows),"valid_count":valid_count,"excluded":excluded,"by_department_yen":totals,"total_yen":sum(totals.values())}
assert result == {"rows":24,"valid_count":20,"excluded":{"duplicate":1,"outside_period":1,"cancelled":1,"missing_amount":1},"by_department_yen":{"営業":70000,"企画":77000,"管理":63000},"total_yen":210000}
print(json.dumps(result,ensure_ascii=False,indent=2))
