"""一次性迁移：对齐 member_retention_clue.category 枚举值"""
import os
import sys
from pathlib import Path

# 加载环境变量
root = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(root))

from dotenv import load_dotenv
load_dotenv(root / ".env")

dsn = os.environ.get("TEST_APP_DB_DSN") or os.environ.get("APP_DB_DSN")
if not dsn:
    print("ERROR: TEST_APP_DB_DSN / APP_DB_DSN 未设置")
    sys.exit(1)

# 强制使用测试库
if "test_zqyy_app" not in dsn:
    print(f"ERROR: DSN 不指向测试库 test_zqyy_app: {dsn[:50]}...")
    sys.exit(1)

sql_file = root / "db" / "zqyy_app" / "migrations" / "2026-03-08__align_retention_clue_category_enum.sql"
sql = sql_file.read_text(encoding="utf-8")

# 提取事务块（BEGIN...COMMIT）
import re
match = re.search(r"(BEGIN;.*?COMMIT;)", sql, re.DOTALL)
if not match:
    print("ERROR: 未找到 BEGIN...COMMIT 块")
    sys.exit(1)

tx_sql = match.group(1)

import psycopg2
print(f"连接: {dsn[:50]}...")
conn = psycopg2.connect(dsn)
try:
    cur = conn.cursor()
    cur.execute(tx_sql)
    conn.commit()
    print("迁移执行成功")

    # 验证
    cur.execute("SELECT COUNT(*) FROM member_retention_clue WHERE category = '客户基础信息'")
    cnt = cur.fetchone()[0]
    print(f"验证: category='客户基础信息' 残留行数 = {cnt} (预期 0)")

    cur.execute("""
        SELECT conname, pg_get_constraintdef(oid)
        FROM pg_constraint
        WHERE conrelid = 'member_retention_clue'::regclass AND contype = 'c'
    """)
    for row in cur.fetchall():
        print(f"约束: {row[0]} => {row[1]}")

    cur.close()
finally:
    conn.close()
