#!/usr/bin/env python3
"""So hai trades.csv của Forward EA (vd EA 4 chế độ vs EA 5 chế độ) từng lệnh.

Khoá ghép: signal_bar_open_time_utc (giờ mở nến tín hiệu c1). Hai file phải cùng số lệnh và cùng thứ tự.
Mọi cột chung đều so chính xác từng ký tự, TRỪ các cột được phép khác:
  strategy_version, account_ref, order_ref (nhãn/magic), signal_to_fill_latency_ms (đồng hồ thật của tester),
  h4_close/h4_ema34/h4_ema89 (chỉ có ở EA 5 chế độ), k_width/k_slope/k_buf khi file A để trống.
Dùng: compare_trades.py A.csv B.csv   → in số khớp/tổng, cột lệch, sha256 hai file. Exit 1 nếu lệch.
"""
import csv, hashlib, sys

ALLOWED = {"strategy_version", "account_ref", "order_ref", "signal_to_fill_latency_ms",
           "h4_close", "h4_ema34", "h4_ema89"}
KEY = "signal_bar_open_time_utc"


def sha(p):
    return hashlib.sha256(open(p, "rb").read()).hexdigest()


def main(a_path, b_path):
    a = list(csv.DictReader(open(a_path)))
    b = list(csv.DictReader(open(b_path)))
    bi = {r[KEY]: r for r in b}
    matched, bad, cols = 0, [], set()
    for r in a:
        s = bi.get(r[KEY])
        if s is None:
            bad.append((r[KEY], "chỉ có ở A")); continue
        diff = [k for k in r if k in s and k not in ALLOWED
                and not (k.startswith("k_") and r[k] == "") and r[k] != s[k]]
        if diff:
            bad.append((r[KEY], diff)); cols.update(diff)
        else:
            matched += 1
    only_b = [k for k in bi if k not in {r[KEY] for r in a}]
    print(f"A {a_path}\n  sha256 {sha(a_path)}  lệnh {len(a)}")
    print(f"B {b_path}\n  sha256 {sha(b_path)}  lệnh {len(b)}")
    print(f"khớp hoàn toàn {matched}/{len(a)} · lệch {len(bad)} · chỉ có ở B {len(only_b)} · cột lệch {sorted(cols) or '-'}")
    for x in bad[:10]:
        print("  ", x)
    return 0 if matched == len(a) == len(b) else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv[1], sys.argv[2]))
