from importlib.machinery import SourceFileLoader


module = SourceFileLoader(
    "v2_stats_weekday_candidate",
    "/opt/charter-live/live_deploy_v2/v2_stats_dashboard.py.weekday_candidate",
).load_module()

data = module.assemble_data()
page = module.render_dashboard(data)
heatmap = data["heatmap"]
total = sum(sum(row) for row in heatmap["matrix_w"]) + sum(
    sum(row) for row in heatmap["matrix_l"]
)
nonempty_days = sum(
    1
    for day_index in range(7)
    if sum(heatmap["matrix_w"][day_index]) + sum(heatmap["matrix_l"][day_index])
)

checks = {
    "integrity_rule": data["classification_integrity"]["rule"]
    == "exact_order_id_or_unique_entry_lifecycle",
    "unclassified_zero": data["classification_integrity"]["unclassified"] == 0,
    "detail_rows_match_total": page.count("data-weekday-trade-row='1'") == total,
    "buttons_match_nonempty_days": page.count("class='weekday-detail-link'") == nonempty_days,
    "dialogs_match_nonempty_days": page.count("class='asset-dialog weekday-dialog'") == nonempty_days,
    "expected_columns": all(
        label in page
        for label in (
            "Apertura",
            "Chiusura",
            "Asset",
            "Strategia",
            "Direzione",
            "Qty",
            "Entry",
            "Exit",
            "Gross",
            "Fee",
            "Net",
            "Close Order ID",
        )
    ),
}

print(f"total_trades={total} nonempty_days={nonempty_days}")
for name, passed in checks.items():
    print(f"{name}={'OK' if passed else 'FAIL'}")
if not all(checks.values()):
    raise SystemExit(1)
