import ctypes
import hashlib
import time
import json
import sys
import os

# 强制刷新输出缓冲区
sys.stdout.reconfigure(line_buffering=True)
sys.stderr.reconfigure(line_buffering=True)

# 创建日志文件
log_file = open("dll_startup.log", "w", encoding="utf-8")

def log_print(msg):
    """同时输出到控制台和日志文件"""
    print(msg)
    log_file.write(msg + "\n")
    log_file.flush()
    sys.stdout.flush()

log_print("=== SaiNiu DLL 启动脚本开始 ===")
log_print(f"Python版本: {sys.version}")
log_print(f"当前工作目录: {os.getcwd()}")
log_print(f"时间戳: {time.strftime('%Y-%m-%d %H:%M:%S')}")

try:
    log_print("正在加载 SaiNiuApi.dll...")
    # 加载DLL文件
    sainiu_api = ctypes.CDLL('SaiNiuApi.dll')
    log_print("[OK] SaiNiuApi.dll 加载成功")

    # 定义函数参数类型和返回值类型
    sainiu_api.Access_ServerStart.argtypes = [
        ctypes.c_int,
        ctypes.c_bool,
        ctypes.c_bool,
        ctypes.c_bool,
        ctypes.c_bool,
        ctypes.c_int,
        ctypes.c_char_p,
        ctypes.c_bool,
        ctypes.c_bool
    ]
    sainiu_api.Access_ServerStart.restype = ctypes.c_char_p
    log_print("[OK] DLL函数类型定义完成")

    # 调用函数时传入的参数
    port = 3030
    web_socket = True
    http_server = True
    remote = False
    log = True
    ws_max = 0
    sign_key = b''
    sha256 = True
    version_tip = True

    log_print(f"正在启动服务器 - 端口: {port}")
    # 启动服务器
    result = sainiu_api.Access_ServerStart(
        port,
        web_socket,
        http_server,
        remote,
        log,
        ws_max,
        sign_key,
        sha256,
        version_tip
    )

    # 解码并打印结果
    try:
        result_str = result.decode('gbk')
        log_print(f"[OK] Access_ServerStart 服务器启动结果: {result_str}")
    except UnicodeDecodeError:
        log_print(f"[OK] Access_ServerStart 服务器启动结果: {result}")

    log_print("=== DLL服务启动完成，进入监控模式 ===")

    # 保持进程运行
    try:
        heartbeat_count = 0
        while True:
            time.sleep(5)
            heartbeat_count += 1
            log_print(f"[HEARTBEAT] DLL服务心跳 #{heartbeat_count} - 服务正常运行中...")
    except KeyboardInterrupt:
        log_print("收到中断信号，正在停止服务...")

except Exception as e:
    log_print(f"[ERROR] DLL启动失败: {e}")
    import traceback
    error_trace = traceback.format_exc()
    log_print(f"错误详情: {error_trace}")
    log_file.close()
    sys.exit(1)
finally:
    if 'log_file' in locals():
        log_file.close()
