"""
Task 14 最终验证脚本：验证种子数据完整性和表结构。
一次性脚本，验证后可删除。
"""
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "apps", "backend"))

from dotenv import load_dotenv
load_dotenv(os.path.join(os.path.dirname(__file__), "..", "..", ".env"))

import psycopg2

dsn = os.environ.get("APP_DB_DSN", "")
if not dsn:
    raise RuntimeError("APP_DB_DSN 未设置")

# 替换为测试库
dsn = dsn.replace("/zqyy_app", "/test_zqyy_app")

conn = psycopg2.connect(dsn)
try:
    with conn.cursor() as cur:
        # 验证种子数据完整性（4 条触发器配置）
        cur.execute(
            "SELECT job_name, job_type, trigger_condition, status "
            "FROM biz.trigger_jobs ORDER BY id"
        )
        rows = cur.fetchall()
        print(f"trigger_jobs 记录数: {len(rows)}")
        for r in rows:
            print(f"  {r[0]} | {r[1]} | {r[2]} | {r[3]}")
        assert len(rows) >= 4, f"期望至少 4 条种子数据，实际 {len(rows)}"

        # 验证表结构
        for tbl in ["coach_tasks", "coach_task_history", "notes", "trigger_jobs"]:
            cur.execute(
                "SELECT count(*) FROM information_schema.tables "
                "WHERE table_schema='biz' AND table_name=%s",
                (tbl,),
            )
            exists = cur.fetchone()[0]
            status = "存在" if exists else "不存在"
            print(f"biz.{tbl}: {status}")
            assert exists, f"biz.{tbl} 不存在"

        # 验证部分唯一索引
        cur.execute(
            "SELECT indexname FROM pg_indexes "
            "WHERE schemaname='biz' AND indexname='idx_coach_tasks_site_assistant_member_type'"
        )
        idx = cur.fetchone()
        print(f"部分唯一索引: {'存在' if idx else '不存在'}")
        assert idx, "idx_coach_tasks_site_assistant_member_type 不存在"

    conn.commit()
    print("\n最终验证全部通过 ✓")
finally:
    conn.close()
