"""
一次性脚本：查看并重置 dev_test_openid 用户的测试数据。
- 删除该用户的所有申请记录
- 将用户状态重置为 new
使用测试库 test_zqyy_app
"""
import os
import sys
from pathlib import Path

# 加载根 .env
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:
    raise RuntimeError("TEST_APP_DB_DSN / APP_DB_DSN 未配置")

# 确保连的是测试库
if "test_zqyy_app" not in dsn:
    raise RuntimeError(f"DSN 不是测试库: {dsn}")

import psycopg2

conn = psycopg2.connect(dsn)
try:
    with conn.cursor() as cur:
        # 查看当前状态
        cur.execute("""
            SELECT u.id, u.wx_openid, u.status, u.nickname,
                   ua.id as app_id, ua.status as app_status, ua.site_code
              FROM auth.users u
              LEFT JOIN auth.user_applications ua ON u.id = ua.user_id
             WHERE u.wx_openid = 'dev_test_openid'
        """)
        rows = cur.fetchall()
        print("=== 当前数据 ===")
        for r in rows:
            print(f"  user_id={r[0]}, openid={r[1]}, user_status={r[2]}, "
                  f"nickname={r[3]}, app_id={r[4]}, app_status={r[5]}, site_code={r[6]}")

        if not rows:
            print("未找到 dev_test_openid 用户")
            sys.exit(0)

        user_id = rows[0][0]

        # 删除申请记录
        cur.execute("DELETE FROM auth.user_applications WHERE user_id = %s", (user_id,))
        deleted = cur.rowcount
        print(f"\n删除 {deleted} 条申请记录")

        # 重置用户状态为 new
        cur.execute(
            "UPDATE auth.users SET status = 'new', updated_at = NOW() WHERE id = %s",
            (user_id,),
        )
        print(f"用户 {user_id} 状态已重置为 new")

        conn.commit()
        print("\n=== 完成 ===")
finally:
    conn.close()
