#!/usr/bin/env python3
"""Create a transaction graph from CSV exports for authorized blockchain forensics."""

from __future__ import annotations

import argparse
import csv
from collections import defaultdict
from pathlib import Path


def main() -> int:
    parser = argparse.ArgumentParser(description="Summarize address graph relationships from transactions CSV.")
    parser.add_argument("csv_file", type=Path, help="CSV with from,to,eth columns")
    parser.add_argument("--dot", type=Path, default=Path("transaction_graph.dot"))
    args = parser.parse_args()

    totals: dict[tuple[str, str], float] = defaultdict(float)
    with args.csv_file.open("r", encoding="utf-8", newline="") as handle:
        for row in csv.DictReader(handle):
            src = row["from"][:10]
            dst = row["to"][:10]
            totals[(src, dst)] += float(row.get("eth") or 0)

    with args.dot.open("w", encoding="utf-8") as handle:
        handle.write("digraph transactions {\n")
        handle.write('  rankdir="LR";\n')
        for (src, dst), amount in sorted(totals.items(), key=lambda item: item[1], reverse=True):
            handle.write(f'  "{src}" -> "{dst}" [label="{amount:.6f} ETH"];\n')
        handle.write("}\n")
    print(f"Wrote Graphviz DOT to {args.dot}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
