#!/usr/bin/env python3
"""
ERP API 配置表初始化脚本 - MySQL版本
在MySQL hzhub数据库中创建配置表
"""

import pymysql
import os
from pathlib import Path

# MySQL数据库连接配置
MYSQL_HOST = os.getenv('MYSQL_HOST', '192.168.120.60')
MYSQL_PORT = int(os.getenv('MYSQL_PORT', '3306'))
MYSQL_DB = os.getenv('MYSQL_DB', 'hzhub')
MYSQL_USER = os.getenv('MYSQL_USERNAME', 'root')
MYSQL_PASSWORD = os.getenv('MYSQL_PASSWORD', 'hzhub123')

print(f"Connecting to MySQL: {MYSQL_HOST}:{MYSQL_PORT}/{MYSQL_DB}")

try:
    # 连接MySQL数据库
    conn = pymysql.connect(
        host=MYSQL_HOST,
        port=MYSQL_PORT,
        database=MYSQL_DB,
        user=MYSQL_USER,
        password=MYSQL_PASSWORD,
        charset='utf8mb4'
    )

    cursor = conn.cursor()

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

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

    # 分割SQL语句（按分号分割，跳过注释和USE语句）
    sql_statements = []
    for statement in sql_content.split(';'):
        statement = statement.strip()
        # 跳过USE语句、注释和空语句
        if not statement or statement.startswith('--') or statement.upper().startswith('USE'):
            continue
        sql_statements.append(statement)

    print(f"Found {len(sql_statements)} SQL statements")

    # 执行每个SQL语句
    for i, statement in enumerate(sql_statements, 1):
        print(f"Executing statement {i}...")
        try:
            cursor.execute(statement)
            conn.commit()
            print(f"✓ Statement {i} executed successfully")
        except Exception as e:
            error_msg = str(e)
            if "already exists" in error_msg or "Duplicate" in error_msg:
                print(f"✓ Statement {i} skipped (already exists)")
            else:
                print(f"✗ Error in statement {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"SHOW TABLES LIKE '{table}'")
        result = cursor.fetchone()
        if result:
            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 in MySQL!")

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