#!/usr/bin/env python3
"""
ERP API 配置表初始化脚本
执行 SQL Server 表创建脚本
"""

import pymssql
import os
from pathlib import Path

# 数据库连接配置（从环境变量或使用默认值）
# 使用 .env 文件中的配置
DB_HOST = os.getenv('ERP_DB_HOST', '192.168.120.10')
DB_PORT = int(os.getenv('ERP_DB_PORT', '8042'))
DB_NAME = os.getenv('ERP_DB_NAME', 'DMPF_HY')
DB_USER = os.getenv('ERP_DB_USERNAME', 'aiuser')
DB_PASSWORD = os.getenv('ERP_DB_PASSWORD', 'aiuser123')

print(f"Connecting to SQL Server: {DB_HOST}:{DB_PORT}/{DB_NAME}")

try:
    # 连接数据库
    conn = pymssql.connect(
        server=DB_HOST,
        port=DB_PORT,
        database=DB_NAME,
        user=DB_USER,
        password=DB_PASSWORD,
        charset='utf8'
    )

    cursor = conn.cursor()

    # 读取SQL文件
    sql_file = Path(__file__).parent / 'docs' / 'sql' / 'erp_api_tables_sqlserver.sql'
    print(f"Reading SQL file: {sql_file}")

    with open(sql_file, 'r', encoding='utf-8') as f:
        sql_content = f.read()

    # 分割SQL语句（按GO分割）
    sql_statements = sql_content.split('GO')

    print(f"Found {len(sql_statements)} SQL statement blocks")

    # 执行每个SQL语句块
    for i, statement in enumerate(sql_statements, 1):
        statement = statement.strip()
        if not statement or statement.startswith('--'):
            continue

        print(f"Executing statement block {i}...")
        try:
            cursor.execute(statement)
            conn.commit()
            print(f"✓ Statement block {i} executed successfully")
        except Exception as e:
            print(f"✗ Error in statement block {i}: {e}")
            # 继续执行其他语句
            conn.rollback()

    # 查询表是否创建成功
    print("\nVerifying tables...")
    tables_to_check = ['erp_api_config', 'erp_api_param', 'erp_api_stats']

    for table in tables_to_check:
        cursor.execute(f"SELECT COUNT(*) FROM sysobjects WHERE name='{table}' AND xtype='U'")
        count = cursor.fetchone()[0]
        if count > 0:
            print(f"✓ Table {table} exists")

            # 显示表的行数
            cursor.execute(f"SELECT COUNT(*) FROM {table}")
            rows = cursor.fetchone()[0]
            print(f"  - Rows: {rows}")
        else:
            print(f"✗ Table {table} NOT found")

    cursor.close()
    conn.close()

    print("\n✓ ERP API configuration tables initialized successfully!")

except pymssql.Error as e:
    print(f"\n✗ Database error: {e}")
    exit(1)
except Exception as e:
    print(f"\n✗ Error: {e}")
    exit(1)