# -*- coding: utf-8 -*-
"""Shared runtime imports for the CLI."""

import argparse
import logging
import os
import subprocess
import sys
from datetime import datetime
from pathlib import Path
from typing import Optional

SRC_DIR = Path(__file__).resolve().parents[2]
if str(SRC_DIR) not in sys.path:
    sys.path.insert(0, str(SRC_DIR))

def _help_example_prog():
    """帮助「示例」中的命令前缀：打包后与源码 python 调用区分。"""
    if getattr(sys, "frozen", False):
        return Path(sys.argv[0]).name if sys.argv else "ServerManager.exe"
    return "python -m entrypoints.cli"


def setup_logging():
    """配置日志系统。日志属于软件配置，与软件一起走（存于 AppData/ServerManager/logs）。"""
    # 创建根日志器
    logger = logging.getLogger('server_manager_command')
    logger.setLevel(logging.DEBUG)
    logger.propagate = False
    if logger.handlers:
        return logger

    log_format = '%(asctime)s [%(levelname)s] %(message)s'
    date_format = '%Y-%m-%d %H:%M:%S'

    try:
        try:
            from models.app_config import get_app_log_dir
            log_dir = get_app_log_dir()
        except ImportError:
            log_dir = Path.cwd() / "logs"
            log_dir.mkdir(exist_ok=True)
        log_file = log_dir / f"server_manager_command_{datetime.now().strftime('%Y%m%d')}.log"

        file_handler = logging.FileHandler(log_file, encoding='utf-8')
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(logging.Formatter(log_format, date_format))
        logger.addHandler(file_handler)
    except Exception:
        # CLI/MCP must still start when the per-user log directory is locked or unavailable.
        logger.addHandler(logging.NullHandler())
    
    return logger


logger = setup_logging()

from services.commands import (
    get_local_ip,
    ensure_and_get_server_manager_config_dir,
    find_existing_default_config_path,
    find_existing_user_config_path,
    get_default_config_path,
    get_project_config_path,
    get_server_manager_config_dir,
    get_user_config_path,
    build_start_command,
    build_start_command_by_config,
    build_stop_command,
    build_remsh_command,
    read_config_file,
    read_merged_config,
    generate_start_config,
    run_startup_migrations,
    get_config_list,
    get_server_list,
    run_cmd_in_new_window,
    run_cmd_foreground,
    subprocess_args_to_display,
    IS_WINDOWS,
    IS_LINUX,
    REBAR3_CMD,
    DEFAULT_CONFIG_FILE,
    LEGACY_DEFAULT_CONFIG_FILE,
    USER_CONFIG_FILE,
    LEGACY_USER_CONFIG_FILE,
    PROJECT_CONFIG_FILE,
)

from services.server_creator import (
    create_server,
    get_existing_server_ids,
    get_default_port,
    generate_server_dir_name,
    get_server_type_name,
    SERVER_TYPE_MAP,
)
