import socket

import uvicorn

from financial_system.core.logger import AppLogger
from financial_system.core.settings import get_settings

logger = AppLogger.get_logger(__name__)


def resolve_port(preferred_port: int, fallback_port: int) -> int:
    """优先使用配置文件端口；被占用时自动切到备用端口。"""
    return preferred_port if is_port_available(preferred_port) else fallback_port


def is_port_available(port: int) -> bool:
    """用一次本地 TCP 探测判断端口是否可绑定。"""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        return sock.connect_ex(("127.0.0.1", port)) != 0


if __name__ == "__main__":
    settings = get_settings()
    AppLogger.configure(settings)
    port = resolve_port(settings.server_port, settings.server_fallback_port)
    logger.info("后端服务启动 host=%s port=%s config_path=%s", settings.server_host, port, settings.config_path)
    uvicorn.run(
        "financial_system.api:app",
        host=settings.server_host,
        port=port,
        reload=False,
    )
