"""
系统配置文件
用于管理系统参数，如缓冲区大小、超时设置等
"""

import os
from dotenv import load_dotenv

# 加载环境变量
load_dotenv()

# 缓冲区配置
MAX_BUFFER_SIZE = 1000  # 数据缓冲区最大条目数
SERIAL_READ_BUFFER_SIZE = 4096  # 串口读取缓冲区大小（字节）

# 串口配置
DEFAULT_BAUDRATE = 9600  # 默认波特率
DEFAULT_SERIAL_TIMEOUT = 1  # 默认串口超时时间（秒）
SERIAL_RECONNECT_INTERVAL = 5  # 串口重连间隔（秒）
SERIAL_RECONNECT_MAX_RETRIES = 5  # 串口最大重连次数

# MQTT配置
DEFAULT_MQTT_PORT = 1883  # 默认MQTT端口
DEFAULT_MQTT_TLS_PORT = 8883  # 默认MQTT TLS端口
DEFAULT_MQTT_KEEPALIVE = 60  # 默认MQTT心跳时间（秒）
MQTT_RECONNECT_INTERVAL = 5  # MQTT重连间隔（秒）
MQTT_RECONNECT_MAX_RETRIES = 5  # MQTT最大重连次数
DEFAULT_MQTT_CLIENT_ID_PREFIX = "serial_mqtt_gateway_"  # 默认MQTT客户端ID前缀
DEFAULT_MQTT_PUBLISH_TOPIC = "serial/data"  # 默认MQTT发布主题
DEFAULT_MQTT_SUBSCRIBE_TOPIC = "command/serial"  # 默认MQTT订阅主题

# WebSocket配置
SOCKETIO_ASYNC_MODE = 'threading'  # SocketIO异步模式
SOCKETIO_MESSAGE_QUEUE = None  # SocketIO消息队列，生产环境可配置Redis
SOCKETIO_TRANSPORTS = ['websocket', 'polling']  # SocketIO传输方式
SOCKETIO_ALLOWED_ORIGINS = '*'  # SocketIO允许的来源

# Flask配置
FLASK_SECRET_KEY = os.getenv('FLASK_SECRET_KEY', 'serial_mqtt_gateway_secret_key')
FLASK_DEBUG = os.getenv('FLASK_DEBUG', 'False').lower() == 'true'
FLASK_HOST = os.getenv('FLASK_HOST', '0.0.0.0')
FLASK_PORT = int(os.getenv('FLASK_PORT', '5001'))

# 日志配置
LOG_LEVEL = os.getenv('LOG_LEVEL', 'INFO')
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
LOG_FILE = os.getenv('LOG_FILE', None)  # 如果设置了值，则将日志写入文件

# 性能配置
MAX_CONCURRENT_SOCKETIO_CLIENTS = 100  # 最大并发SocketIO客户端数
SOCKETIO_HEARTBEAT_INTERVAL = 25  # SocketIO心跳间隔（秒）
SOCKETIO_HEARTBEAT_TIMEOUT = 30  # SocketIO心跳超时（秒）

# 转发配置
DEFAULT_FORWARD_SERIAL_TO_MQTT = False  # 默认是否启用串口到MQTT转发
DEFAULT_FORWARD_MQTT_TO_SERIAL = False  # 默认是否启用MQTT到串口转发

# 主题配置
SOCKETIO_NAMESPACE_DATA = '/data'  # 数据命名空间
SOCKETIO_NAMESPACE_STATUS = '/status'  # 状态命名空间
SOCKETIO_NAMESPACE_CONTROL = '/control'  # 控制命名空间

# API路径配置
API_PREFIX = '/api'
API_SERIAL_PREFIX = f'{API_PREFIX}/serial'
API_MQTT_PREFIX = f'{API_PREFIX}/mqtt'
API_DATA_PREFIX = f'{API_PREFIX}/data'
API_FORWARD_PREFIX = f'{API_PREFIX}/forward'
API_HEALTH = f'{API_PREFIX}/health'

# 错误码定义
ERROR_CODES = {
    'SUCCESS': 0,
    'SERIAL_CONNECTION_ERROR': 1001,
    'SERIAL_SEND_ERROR': 1002,
    'SERIAL_RECEIVE_ERROR': 1003,
    'MQTT_CONNECTION_ERROR': 2001,
    'MQTT_PUBLISH_ERROR': 2002,
    'MQTT_SUBSCRIBE_ERROR': 2003,
    'CONFIG_ERROR': 3001,
    'NETWORK_ERROR': 4001,
    'UNKNOWN_ERROR': 9999
}

# 错误消息定义
ERROR_MESSAGES = {
    ERROR_CODES['SUCCESS']: '成功',
    ERROR_CODES['SERIAL_CONNECTION_ERROR']: '串口连接失败',
    ERROR_CODES['SERIAL_SEND_ERROR']: '串口发送数据失败',
    ERROR_CODES['SERIAL_RECEIVE_ERROR']: '串口接收数据失败',
    ERROR_CODES['MQTT_CONNECTION_ERROR']: 'MQTT连接失败',
    ERROR_CODES['MQTT_PUBLISH_ERROR']: 'MQTT发布消息失败',
    ERROR_CODES['MQTT_SUBSCRIBE_ERROR']: 'MQTT订阅主题失败',
    ERROR_CODES['CONFIG_ERROR']: '配置错误',
    ERROR_CODES['NETWORK_ERROR']: '网络错误',
    ERROR_CODES['UNKNOWN_ERROR']: '未知错误'
}

# DTU配置
DEFAULT_CUSTOMER_ID = os.getenv('CUSTOMER_ID', 'default_customer')
DEFAULT_DTU_ID = os.getenv('DTU_ID', 'dtu_001')
DTU_HEARTBEAT_INTERVAL = 60  # DTU状态上报间隔（秒） - 协议 7.13 要求
DTU_OFFLINE_TIMEOUT = 180    # DTU 离线判定超时（秒） - 协议 7.13 要求

# MQTT主题前缀（可配置 - 通过web界面设置）
DEFAULT_MQTT_TOPIC_PREFIX = os.getenv('MQTT_TOPIC_PREFIX', '线架系统')

# DTU MQTT主题模板（运行时根据topic_prefix动态生成）
# 格式: {topic_prefix}/{customer_id}/dtu/{dtu_id}/{topic}
DTU_REGISTRATION_TOPIC = 'register'
DTU_STATUS_TOPIC = 'status'
DTU_CONTROL_TOPIC = 'control'
DTU_RESPONSE_TOPIC = 'response'
DTU_EVENT_TOPIC = 'event'
DTU_ALARM_TOPIC = 'alarm'
DTU_BROADCAST_TOPIC = 'broadcast'

# 面板配置
MAX_PANELS = 8  # 最大面板数
MAX_PORTS_PER_PANEL = 24  # 每个面板最大端口数

# DHT11 环境传感器配置（本地 GPIO 读取）
DHT11_ENABLED = os.getenv('DHT11_ENABLED', 'true').lower() in ('1', 'true', 'yes')
DHT11_GPIO_PIN = int(os.getenv('DHT11_GPIO_PIN')) if os.getenv('DHT11_GPIO_PIN') else None
DHT11_GPIO_CHIP = os.getenv('DHT11_GPIO_CHIP', 'gpiochip0')
DHT11_POLL_INTERVAL = int(os.getenv('DHT11_POLL_INTERVAL', '5'))
DHT11_SIMULATE = os.getenv('DHT11_SIMULATE', 'false').lower() in ('1', 'true', 'yes')
DHT11_MAX_HISTORY = 1000  # 保留最近 1000 条历史记录