"""DEBUG 第四轮：ODS settlement_records 的 member 列名 + 负值来源。"""
import psycopg2, psycopg2.extras, os
from dotenv import load_dotenv
from pathlib import Path

load_dotenv(Path(__file__).resolve().parents[2] / ".env")
conn = psycopg2.connect(os.environ["PG_DSN"])
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)

member_id = 2799207378798341
site_id = 2790685415443269

# ODS settlement_records 的 member 相关列
cur.execute("""
    SELECT column_name FROM information_schema.columns
    WHERE table_schema='ods' AND table_name='settlement_records'
      AND column_name LIKE '%%member%%'
""")
print("=== ods.settlement_records member 列 ===")
for r in cur.fetchall():
    print(f"  {r['column_name']}")

# 用 tenantmemberid (API 原始驼峰转小写)
cur.execute("""
    SELECT column_name FROM information_schema.columns
    WHERE table_schema='ods' AND table_name='settlement_records'
      AND column_name LIKE '%%tenant%%'
""")
print("\n=== ods.settlement_records tenant 列 ===")
for r in cur.fetchall():
    print(f"  {r['column_name']}")

# 查 DWD mapping 中 tenant_member_id 的来源
# dwd_settlement_head 有 member_id，ODS 有什么？
cur.execute("""
    SELECT consumemoney, id
    FROM ods.settlement_records
    WHERE consumemoney < 0
    ORDER BY consumemoney LIMIT 5
""")
print("\n=== ODS 负值 consumemoney 记录 ===")
for r in cur.fetchall():
    print(f"  consumemoney={r['consumemoney']}, id={r['id']}")

# 确认 dwd_settlement_head 没有 tenant_member_id
cur.execute("""
    SELECT column_name FROM information_schema.columns
    WHERE table_schema='dwd' AND table_name='dwd_settlement_head'
      AND column_name LIKE '%%tenant%%member%%'
""")
rows = cur.fetchall()
print(f"\n=== dwd_settlement_head tenant_member 列: {[r['column_name'] for r in rows]} ===")
if not rows:
    print("  确认: dwd_settlement_head 没有 tenant_member_id 列")
    print("  member_visit_task.py 第326行引用 tenant_member_id 是 BUG")
    print("  正确列名应为 member_id")

conn.close()
