import json
from datetime import datetime, timezone

DATE_STR = "2026-06-20"

# Read both chunks
chunk1_path = f"/home/kiro/trend-engine/trends/x/account-monitor/scan_results_{DATE_STR}_CHUNK1.json"
chunk2_path = f"/home/kiro/trend-engine/trends/x/account-monitor/scan_results_{DATE_STR}_CHUNK2.json"

with open(chunk1_path) as f:
    c1 = json.load(f)
with open(chunk2_path) as f:
    c2 = json.load(f)

merged = {
    "accounts": c1["accounts"] + c2["accounts"],
    "errors": c1["errors"] + c2["errors"],
    "scan_date": f"{DATE_STR} 06:00 UTC"
}

print(f"Merged: {len(merged['accounts'])} accounts, {len(merged['errors'])} errors")

# Verify date filter: check that all tweets in qualifying list are within 3 days of 2026-06-20
cutoff = datetime.strptime("2026-06-17 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z")

bad_dates = 0
for acc in merged["accounts"]:
    for t in acc["tweets"]:
        date_str = t.get("date", "")
        if not date_str:
            print(f"  WARN: {acc['handle']} - tweet with no date")
            bad_dates += 1
            continue
        dt = datetime.strptime(date_str + " 00:00:00 +0000", "%Y-%m-%d %H:%M:%S %z")
        if dt < cutoff:
            print(f"  OLD TWEET: {acc['handle']} - {date_str} - {t['text'][:60]}...")
            bad_dates += 1

if bad_dates == 0:
    print("ALL DATES VALID - no tweets older than 3 days")
else:
    print(f"FOUND {bad_dates} OLD TWEETS")

# Stats
total_qualifying = sum(acc["qualifying_count"] for acc in merged["accounts"])
accounts_with_content = sum(1 for acc in merged["accounts"] if acc["qualifying_count"] > 0)
print(f"Total qualifying tweets: {total_qualifying}")
print(f"Accounts with content: {accounts_with_content}")

# Save merged
out_path = f"/home/kiro/trend-engine/trends/x/account-monitor/scan_results_{DATE_STR}.json"
with open(out_path, "w") as f:
    json.dump(merged, f, indent=2)
print(f"Merged saved to {out_path}")
