# -*- coding: utf-8 -*-
"""检查迁移脚本中定义的 (pk, fetched_at DESC) 索引是否存在于数据库中。"""
import os
import sys
from pathlib import Path
from dotenv import load_dotenv
import psycopg2

env_path = Path(__file__).resolve().parents[2] / "apps" / "etl" / "pipelines" / "feiqiu" / ".env"
load_dotenv(env_path)

dsn = os.environ.get("PG_DSN")
if not dsn:
    print("ERROR: PG_DSN 未配置")
    sys.exit(1)

conn = psycopg2.connect(dsn, connect_timeout=10)
cur = conn.cursor()

# 迁移脚本中定义的 23 个 _latest 索引
expected = [
    "idx_ods_assistant_accounts_master_latest",
    "idx_ods_settlement_records_latest",
    "idx_ods_table_fee_transactions_latest",
    "idx_ods_assistant_service_records_latest",
    "idx_ods_store_goods_sales_records_latest",
    "idx_ods_payment_transactions_latest",
    "idx_ods_refund_transactions_latest",
    "idx_ods_platform_coupon_redemption_records_latest",
    "idx_ods_member_profiles_latest",
    "idx_ods_member_stored_value_cards_latest",
    "idx_ods_member_balance_changes_latest",
    "idx_ods_recharge_settlements_latest",
    "idx_ods_group_buy_packages_latest",
    "idx_ods_group_buy_redemption_records_latest",
    "idx_ods_goods_stock_summary_latest",
    "idx_ods_goods_stock_movements_latest",
    "idx_ods_site_tables_master_latest",
    "idx_ods_stock_goods_category_tree_latest",
    "idx_ods_store_goods_master_latest",
    "idx_ods_table_fee_discount_records_latest",
    "idx_ods_tenant_goods_master_latest",
]

cur.execute("""
    SELECT indexname FROM pg_indexes WHERE schemaname = 'ods'
""")
existing = {row[0] for row in cur.fetchall()}

print("迁移脚本 (pk, fetched_at DESC) 索引检查：")
for idx in expected:
    status = "✓ 存在" if idx in existing else "✗ 缺失"
    print(f"  {status}  {idx}")

missing = [idx for idx in expected if idx not in existing]
print(f"\n共 {len(expected)} 个，缺失 {len(missing)} 个")

cur.close()
conn.close()
