"""
后台预热模块：在 import zsdtdx 时非阻塞预热连接池

职责：
1. 在模块导入时启动后台线程预热连接池。
2. 非阻塞式建立标准/扩展行情连接，加速后续请求。
3. 提供预热状态查询和等待接口。

边界：
1. 预热失败不阻塞主流程，仅记录状态。
2. 预热连接在完成后立即关闭，避免资源占用。
"""
import os
import threading
import time
from pathlib import Path

import yaml

# 禁止代理
os.environ["NO_PROXY"] = "*"
os.environ["no_proxy"] = "*"

_warmup_thread = None
_warmup_status = {
    "started": False,
    "completed": False,
    "std_ready": False,
    "ex_ready": False,
    "error": None
}

def _load_config():
    """加载配置"""
    config_path = Path(__file__).parent / "config.yaml"
    try:
        with open(config_path, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)
    except Exception:
        return {}

def _do_warmup():
    """执行预热"""
    global _warmup_status
    
    try:
        config = _load_config()
        warmup_size = config.get("pool", {}).get("warmup_connections", 0)
        
        if warmup_size <= 0:
            _warmup_status["completed"] = True
            return
        
        # 延迟导入避免循环依赖
        from .wrapper.unified_client import UnifiedTdxClient
        
        config_path = str(Path(__file__).parent / "config.yaml")
        client = UnifiedTdxClient(config_path=config_path)
        
        # 预热标准行情
        try:
            client.std_pool.ensure_connected()
            _warmup_status["std_ready"] = True
        except Exception as e:
            _warmup_status["error"] = f"std warmup failed: {e}"
        
        # 预热扩展行情
        try:
            client.ex_pool.ensure_connected()
            _warmup_status["ex_ready"] = True
        except Exception as e:
            _warmup_status["error"] = f"ex warmup failed: {e}"
        
        _warmup_status["completed"] = True
        
    except Exception as e:
        _warmup_status["error"] = str(e)
    finally:
        # 关闭 client 释放资源（预热只建立连接，不保持）
        try:
            client.close()
        except:
            pass

def start_background_warmup():
    """启动后台预热线程"""
    global _warmup_thread, _warmup_status
    
    if _warmup_thread is not None and _warmup_thread.is_alive():
        return  # 已在运行
    
    _warmup_status["started"] = True
    _warmup_thread = threading.Thread(target=_do_warmup, daemon=True)
    _warmup_thread.start()

def get_warmup_status():
    """获取预热状态"""
    return _warmup_status.copy()

def wait_for_warmup(timeout: float = 30.0) -> bool:
    """
    等待预热完成
    
    Args:
        timeout: 最大等待时间（秒）
        
    Returns:
        是否成功完成预热
    """
    if _warmup_thread is None:
        return False
    
    start = time.time()
    while time.time() - start < timeout:
        if _warmup_status["completed"]:
            return True
        time.sleep(0.1)
    
    return _warmup_status["completed"]

# 启动后台预热
start_background_warmup()
