"""验证+修复 2026-02-24 迁移：直接执行 ALTER TABLE 语句"""
import os
import sys
from pathlib import Path
from dotenv import load_dotenv

root = Path(__file__).resolve().parent.parent.parent
load_dotenv(root / ".env")

dsn = os.environ.get("TEST_DB_DSN")
if not dsn:
    print("ERROR: TEST_DB_DSN 未设置", file=sys.stderr)
    sys.exit(1)

import psycopg2

conn = psycopg2.connect(dsn)
conn.autocommit = True
try:
    with conn.cursor() as cur:
        # 先检查列是否已存在
        cur.execute("""
            SELECT column_name FROM information_schema.columns
            WHERE table_schema = 'ods' AND table_name = 'store_goods_master'
              AND column_name IN ('warning_sales_day', 'warning_day_max', 'warning_day_min')
        """)
        existing = [r[0] for r in cur.fetchall()]
        print(f"ODS 已有列: {existing}")

        if len(existing) < 3:
            print("ODS 列不完整，执行 ALTER TABLE...")
            cur.execute("""
                ALTER TABLE ods.store_goods_master
                    ADD COLUMN IF NOT EXISTS warning_sales_day NUMERIC(18,2),
                    ADD COLUMN IF NOT EXISTS warning_day_max INTEGER,
                    ADD COLUMN IF NOT EXISTS warning_day_min INTEGER
            """)
            cur.execute("""
                COMMENT ON COLUMN ods.store_goods_master.warning_sales_day IS
                    '库存预警参考的日均销量。来源：goodsStockWarningInfo.sales_day';
                COMMENT ON COLUMN ods.store_goods_master.warning_day_max IS
                    '库存预警天数上限。来源：goodsStockWarningInfo.warning_day_max';
                COMMENT ON COLUMN ods.store_goods_master.warning_day_min IS
                    '库存预警天数下限。来源：goodsStockWarningInfo.warning_day_min';
            """)
            print("ODS ALTER 完成")

        cur.execute("""
            SELECT column_name FROM information_schema.columns
            WHERE table_schema = 'dwd' AND table_name = 'dim_store_goods_ex'
              AND column_name IN ('warning_sales_day', 'warning_day_max', 'warning_day_min')
        """)
        existing_dwd = [r[0] for r in cur.fetchall()]
        print(f"DWD 已有列: {existing_dwd}")

        if len(existing_dwd) < 3:
            print("DWD 列不完整，执行 ALTER TABLE...")
            cur.execute("""
                ALTER TABLE dwd.dim_store_goods_ex
                    ADD COLUMN IF NOT EXISTS warning_sales_day NUMERIC(18,2),
                    ADD COLUMN IF NOT EXISTS warning_day_max INTEGER,
                    ADD COLUMN IF NOT EXISTS warning_day_min INTEGER
            """)
            cur.execute("""
                COMMENT ON COLUMN dwd.dim_store_goods_ex.warning_sales_day IS
                    '库存预警参考的日均销量。来源：goodsStockWarningInfo.sales_day';
                COMMENT ON COLUMN dwd.dim_store_goods_ex.warning_day_max IS
                    '库存预警天数上限。来源：goodsStockWarningInfo.warning_day_max';
                COMMENT ON COLUMN dwd.dim_store_goods_ex.warning_day_min IS
                    '库存预警天数下限。来源：goodsStockWarningInfo.warning_day_min';
            """)
            print("DWD ALTER 完成")

    # 最终验证
    with conn.cursor() as cur:
        cur.execute("""
            SELECT column_name, data_type FROM information_schema.columns
            WHERE table_schema = 'ods' AND table_name = 'store_goods_master'
              AND column_name IN ('warning_sales_day', 'warning_day_max', 'warning_day_min')
            ORDER BY column_name
        """)
        print(f"\n最终验证 ODS: {cur.fetchall()}")

        cur.execute("""
            SELECT column_name, data_type FROM information_schema.columns
            WHERE table_schema = 'dwd' AND table_name = 'dim_store_goods_ex'
              AND column_name IN ('warning_sales_day', 'warning_day_max', 'warning_day_min')
            ORDER BY column_name
        """)
        print(f"最终验证 DWD: {cur.fetchall()}")

finally:
    conn.close()
