"""查询 DWD 层各表的最新记录时间和行数（修正版）。"""
import os
import sys
from dotenv import load_dotenv

load_dotenv()

PG_DSN = os.environ.get("TEST_DB_DSN") or os.environ.get("PG_DSN")
if not PG_DSN:
    print("ERROR: TEST_DB_DSN / PG_DSN 未设置", file=sys.stderr)
    sys.exit(1)

if "etl_feiqiu" in PG_DSN and "test_" not in PG_DSN:
    PG_DSN = PG_DSN.replace("etl_feiqiu", "test_etl_feiqiu")

import psycopg2

# 修正：只查 create_time，不查不存在的 update_time
QUERIES = [
    ("dwd_table_fee_log", "SELECT MAX(create_time), COUNT(*) FROM dwd.dwd_table_fee_log"),
    ("dwd_assistant_service_log", "SELECT MAX(create_time), COUNT(*) FROM dwd.dwd_assistant_service_log"),
    ("dwd_groupbuy_redemption", "SELECT MAX(create_time), COUNT(*) FROM dwd.dwd_groupbuy_redemption"),
    ("dwd_refund", "SELECT MAX(create_time), COUNT(*) FROM dwd.dwd_refund"),
    ("dwd_platform_coupon_redemption", "SELECT MAX(create_time), COUNT(*) FROM dwd.dwd_platform_coupon_redemption"),
]

conn = psycopg2.connect(PG_DSN)
try:
    cur = conn.cursor()
    print(f"{'表名':<42} {'max(create_time)':<30} {'行数':>8}")
    print("-" * 82)
    for tbl, sql in QUERIES:
        try:
            cur.execute(sql)
            row = cur.fetchone()
            t1 = str(row[0])[:25] if row[0] else "-"
            cnt = row[1] if row[1] else 0
            print(f"{tbl:<42} {t1:<30} {cnt:>8}")
        except Exception as e:
            print(f"{tbl:<42} ERROR: {e}")
            conn.rollback()
finally:
    conn.close()
