#!/usr/bin/env python3
"""
ERP API 配置表初始化脚本 - 简化版本
直接创建表，不检查是否存在
"""

import pymssql
import os

# 数据库连接配置
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}")

conn = pymssql.connect(
    server=DB_HOST,
    port=DB_PORT,
    database=DB_NAME,
    user=DB_USER,
    password=DB_PASSWORD,
    charset='utf8'
)

cursor = conn.cursor()

# 1. 创建 erp_api_config 表
print("Creating erp_api_config table...")
try:
    cursor.execute("""
        CREATE TABLE erp_api_config (
            api_id BIGINT IDENTITY(1,1) PRIMARY KEY,
            api_name NVARCHAR(100) NOT NULL,
            api_path NVARCHAR(200) NOT NULL,
            api_method NVARCHAR(10) NOT NULL DEFAULT 'GET',
            api_desc NVARCHAR(500),
            api_version NVARCHAR(10) DEFAULT 'v1',
            data_source NVARCHAR(50) DEFAULT 'erp',
            sql_template NVARCHAR(MAX) NOT NULL,
            result_type NVARCHAR(20) NOT NULL DEFAULT 'LIST',
            support_pagination TINYINT DEFAULT 0,
            page_param_name NVARCHAR(50) DEFAULT 'pageNum',
            size_param_name NVARCHAR(50) DEFAULT 'pageSize',
            require_auth TINYINT DEFAULT 0,
            permission_code NVARCHAR(100),
            enable_cache TINYINT DEFAULT 0,
            cache_key_template NVARCHAR(200),
            cache_ttl INT DEFAULT 300,
            source_table NVARCHAR(100),
            source_table_comment NVARCHAR(500),
            status TINYINT DEFAULT 1,
            create_time DATETIME DEFAULT GETDATE(),
            update_time DATETIME DEFAULT GETDATE(),
            create_by NVARCHAR(50),
            update_by NVARCHAR(50),
            remark NVARCHAR(500)
        )
    """)
    conn.commit()
    print("✓ erp_api_config created")
except Exception as e:
    if "already exists" in str(e):
        print("✓ erp_api_config already exists")
    else:
        print(f"✗ Error creating erp_api_config: {e}")
        conn.rollback()

# 创建索引
print("Creating indexes on erp_api_config...")
try:
    cursor.execute("CREATE INDEX idx_api_path_method ON erp_api_config(api_path, api_method, api_version)")
    conn.commit()
    print("✓ idx_api_path_method created")
except Exception as e:
    if "already exists" in str(e):
        print("✓ idx_api_path_method already exists")
    else:
        print(f"Note: {e}")
        conn.rollback()

try:
    cursor.execute("CREATE INDEX idx_status ON erp_api_config(status)")
    conn.commit()
    print("✓ idx_status created")
except Exception as e:
    if "already exists" in str(e):
        print("✓ idx_status already exists")
    else:
        print(f"Note: {e}")
        conn.rollback()

# 2. 创建 erp_api_param 表
print("Creating erp_api_param table...")
try:
    cursor.execute("""
        CREATE TABLE erp_api_param (
            param_id BIGINT IDENTITY(1,1) PRIMARY KEY,
            api_id BIGINT NOT NULL,
            param_name NVARCHAR(100) NOT NULL,
            param_desc NVARCHAR(500),
            param_type NVARCHAR(20) NOT NULL DEFAULT 'String',
            param_position NVARCHAR(20) NOT NULL DEFAULT 'QUERY',
            is_required TINYINT DEFAULT 0,
            default_value NVARCHAR(200),
            sql_param_name NVARCHAR(100),
            sort INT DEFAULT 0,
            create_time DATETIME DEFAULT GETDATE(),
            update_time DATETIME DEFAULT GETDATE()
        )
    """)
    conn.commit()
    print("✓ erp_api_param created")
except Exception as e:
    if "already exists" in str(e):
        print("✓ erp_api_param already exists")
    else:
        print(f"✗ Error creating erp_api_param: {e}")
        conn.rollback()

# 创建索引和外键
print("Creating indexes on erp_api_param...")
try:
    cursor.execute("CREATE INDEX idx_api_id ON erp_api_param(api_id)")
    conn.commit()
    print("✓ idx_api_id created")
except Exception as e:
    if "already exists" in str(e):
        print("✓ idx_api_id already exists")
    else:
        print(f"Note: {e}")
        conn.rollback()

# 3. 创建 erp_api_stats 表
print("Creating erp_api_stats table...")
try:
    cursor.execute("""
        CREATE TABLE erp_api_stats (
            stats_id BIGINT IDENTITY(1,1) PRIMARY KEY,
            api_id BIGINT NOT NULL,
            call_time DATETIME NOT NULL,
            call_params NVARCHAR(MAX),
            response_time INT,
            call_status NVARCHAR(10),
            error_message NVARCHAR(MAX),
            error_stack NVARCHAR(MAX),
            client_ip NVARCHAR(50),
            user_id NVARCHAR(50),
            create_time DATETIME DEFAULT GETDATE()
        )
    """)
    conn.commit()
    print("✓ erp_api_stats created")
except Exception as e:
    if "already exists" in str(e):
        print("✓ erp_api_stats already exists")
    else:
        print(f"✗ Error creating erp_api_stats: {e}")
        conn.rollback()

# 创建索引
print("Creating indexes on erp_api_stats...")
try:
    cursor.execute("CREATE INDEX idx_api_id_time ON erp_api_stats(api_id, call_time)")
    conn.commit()
    print("✓ idx_api_id_time created")
except Exception as e:
    if "already exists" in str(e):
        print("✓ idx_api_id_time already exists")
    else:
        print(f"Note: {e}")
        conn.rollback()

# 验证表创建
print("\nVerifying tables...")
cursor.execute("SELECT name FROM sysobjects WHERE xtype='U' AND name LIKE 'erp_api_%' ORDER BY name")
tables = cursor.fetchall()

for table in tables:
    print(f"✓ Table {table[0]} created successfully")

cursor.close()
conn.close()

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