"""Read-only synthetic examples from sarnaker.com/guides. Python 3.9+.

Download all CSV files into the same directory as this script, then run:
    python seo-worked-examples.py
No network calls, dependencies or writes. These are not Odoo/Shopify schemas.
"""
import argparse
import csv
import json
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parent


def read_csv(name):
    with (ROOT / name).open(encoding="utf-8-sig", newline="") as handle:
        return list(csv.DictReader(handle))


def grouped(rows, field):
    result = defaultdict(list)
    for row in rows:
        if not row[field].strip():
            raise ValueError(f"Missing {field}")
        result[row[field]].append(row)
    return result


def migration():
    source = read_csv("migration-source.csv")
    target = read_csv("migration-target.csv")
    # This demo deliberately has a single currency. Reject a changed assumption.
    if any(row["currency"] != "CAD" for row in source + target):
        raise ValueError("Migration demo only supports CAD; never sum currencies")
    left, right = grouped(source, "external_id"), grouped(target, "external_id")
    issues = []
    for label, groups in (("source", left), ("target", right)):
        for key in sorted(groups):
            if len(groups[key]) != 1:
                issues.append(f"duplicate {label}: {key}")
    issues.extend(f"missing target: {key}" for key in sorted(left.keys() - right.keys()))
    issues.extend(f"unexpected target: {key}" for key in sorted(right.keys() - left.keys()))
    for key in sorted(left.keys() & right.keys()):
        if len(left[key]) == len(right[key]) == 1:
            if int(left[key][0]["amount_cents"]) != int(right[key][0]["amount_cents"]):
                issues.append(f"amount mismatch: {key}")
    return {"decision": "hold" if issues else "ready for business review", "source_rows": len(source), "target_rows": len(target), "source_cents": sum(int(r["amount_cents"]) for r in source), "target_cents": sum(int(r["amount_cents"]) for r in target), "issues": issues}


def dashboard():
    rows = read_csv("dashboard-invoices.csv")
    if any(len(items) != 1 for items in grouped(rows, "document_id").values()):
        raise ValueError("Duplicate document IDs: check grain before aggregation")
    start = datetime(2026, 9, 1, tzinfo=timezone.utc)
    end = datetime(2026, 10, 1, tzinfo=timezone.utc)
    included, excluded = [], []
    for row in rows:
        issued = datetime.fromisoformat(row["issued_at"].replace("Z", "+00:00"))
        if issued.tzinfo is None:
            raise ValueError("Date requires an explicit timezone")
        amount = int(row["subtotal_cents"])
        reasons = []
        if row["status"] != "posted":
            reasons.append("not posted")
        if row["currency"] != "CAD":
            reasons.append("not CAD")
        if not start <= issued < end:
            reasons.append("outside September UTC")
        if reasons:
            excluded.append({"id": row["document_id"], "reasons": reasons})
        else:
            included.append({"id": row["document_id"], "cents": amount})
    return {"metric": "September 2026 posted CAD subtotal excluding tax", "total_cents": sum(item["cents"] for item in included), "included": included, "excluded": excluded}


def stock():
    rows = read_csv("stock-diagnosis.csv")
    keys = [(r["variant_id"], r["odoo_warehouse"], r["shopify_location"]) for r in rows]
    if len(keys) != len(set(keys)):
        raise ValueError("Duplicate location mappings")
    result = []
    for row in rows:
        if row["rule"] != "on_hand_minus_reserved":
            raise ValueError("Unexpected demo quantity rule")
        available = int(row["on_hand"]) - int(row["reserved"])
        result.append({"warehouse": row["odoo_warehouse"], "location": row["shopify_location"], "comparable_available": available, "difference": available - int(row["shopify_available"])})
    return result


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("example", nargs="?", choices=("migration", "dashboard", "stock", "all"), default="all")
    args = parser.parse_args()
    checks = {"migration": migration, "dashboard": dashboard, "stock": stock}
    selected = checks if args.example == "all" else {args.example: checks[args.example]}
    print(json.dumps({"synthetic_data": True, **{name: run() for name, run in selected.items()}}, indent=2))
