"""
修复并执行之前失败的 DDL/种子：
1. etl_feiqiu: app.sql（视图已修复）
2. etl_feiqiu: 种子数据（schema 引用已修复）
3. zqyy_app: init.sql（BOM 已移除）
"""
import os
import sys
import psycopg2

DB_HOST = "100.64.0.4"
DB_PORT = 5432
DB_USER = "local-Python"
DB_PASSWORD = "Neo-local-1991125"
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


def execute_sql_file(conn, filepath, label=""):
    full_path = os.path.join(BASE_DIR, filepath)
    if not os.path.exists(full_path):
        print(f"  [SKIP] 文件不存在: {filepath}")
        return False
    with open(full_path, "r", encoding="utf-8-sig") as f:
        sql = f.read()
    if not sql.strip():
        print(f"  [SKIP] 文件为空: {filepath}")
        return False
    try:
        cur = conn.cursor()
        cur.execute(sql)
        conn.commit()
        print(f"  [OK] {label or filepath}")
        return True
    except Exception as e:
        conn.rollback()
        print(f"  [FAIL] {label or filepath}: {e}")
        return False


def main():
    print("=== 修复 etl_feiqiu 剩余项 ===")
    conn_etl = psycopg2.connect(
        host=DB_HOST, port=DB_PORT, user=DB_USER,
        password=DB_PASSWORD, dbname="etl_feiqiu"
    )
    conn_etl.autocommit = False

    # app.sql 视图（已修复列名）
    execute_sql_file(conn_etl, "db/etl_feiqiu/schemas/app.sql", "app schema（视图已修复）")

    # 种子数据（schema 引用已修复）
    execute_sql_file(conn_etl, "db/etl_feiqiu/seeds/seed_ods_tasks.sql", "种子：ODS 任务")
    execute_sql_file(conn_etl, "db/etl_feiqiu/seeds/seed_scheduler_tasks.sql", "种子：调度任务")
    # seed_dws_config.sql 整体被注释，跳过
    execute_sql_file(conn_etl, "db/etl_feiqiu/seeds/seed_index_parameters.sql", "种子：指数参数")
    conn_etl.close()

    print("\n=== 修复 zqyy_app 剩余项 ===")
    conn_app = psycopg2.connect(
        host=DB_HOST, port=DB_PORT, user=DB_USER,
        password=DB_PASSWORD, dbname="zqyy_app"
    )
    conn_app.autocommit = False

    # init.sql（BOM 已移除）
    execute_sql_file(conn_app, "db/zqyy_app/schemas/init.sql", "zqyy_app schema（BOM 已修复）")
    conn_app.close()

    print("\n完成。")


if __name__ == "__main__":
    main()
