# -*- coding: utf-8 -*-
"""Run-directory discovery and log-file helpers."""

from .shared import *

def get_config_list(run_dir: str) -> List[str]:
    """获取所有带有 kv.config 的服务器目录列表
    
    Args:
        run_dir: 运行目录路径
    
    Returns:
        服务器目录名列表
    """
    run_path = Path(run_dir)
    if not run_path.exists():
        return []
    
    servers = []
    for item in run_path.iterdir():
        if item.is_dir():
            kv_config = item / 'config' / 'kv.config'
            if kv_config.exists():
                servers.append(item.name)
    return sorted(servers)


def get_server_list(run_dir: str) -> Dict[str, List[str]]:
    """获取服务器列表，按类型分组（不过滤前缀，显示所有服务器目录）
    
    Args:
        run_dir: 运行目录路径
    
    Returns:
        按类型分组的服务器字典
    """
    servers = {
        'game': [],
        'cross': [],
        'login': [],
        'client': [],
        'center': [],
        'other': []
    }
    
    run_path = Path(run_dir)
    if not run_path.exists():
        return servers
    
    for item in run_path.iterdir():
        if not item.is_dir():
            continue
        
        name = item.name
        
        # 检查是否有配置目录（确认是有效的服务器目录）
        if not (item / 'config').exists():
            continue
        
        # 根据目录名中的关键字分类
        name_lower = name.lower()
        if '_game_s' in name_lower or '_game_' in name_lower:
            servers['game'].append(name)
        elif '_cross_s' in name_lower or '_cross_' in name_lower:
            servers['cross'].append(name)
        elif '_login_s' in name_lower or '_login_' in name_lower:
            servers['login'].append(name)
        elif '_client_s' in name_lower or '_client_' in name_lower:
            servers['client'].append(name)
        elif '_center_s' in name_lower or '_center_' in name_lower:
            servers['center'].append(name)
        else:
            # 其他有效服务器目录
            servers['other'].append(name)
    
    return servers


def flatten_server_dirs(run_dir: str) -> List[str]:
    """按类型顺序返回 run 目录下所有有效服务器子目录名。"""
    order = ('game', 'cross', 'login', 'client', 'center', 'other')
    buckets = get_server_list(run_dir)
    out: List[str] = []
    for k in order:
        out.extend(sorted(buckets.get(k, [])))
    return out


def resolve_log_file_path(
    run_dir: str,
    server_dir: str,
    base_filename: str,
    date_yyyymmdd: Optional[str] = None,
    subdir: str = "",
) -> Path:
    """解析日志文件路径。

    无日期：``log/[subdir/]base_filename``（如 error.log）
    有日期：``log/[subdir/]base_filename.YYYYMMDD``（如 error.log.20260305）

    Args:
        run_dir: 运行根目录（含 run）
        server_dir: 服务器目录名（如 ddxq_ai002_game_s100）
        base_filename: 主文件名，如 error.log、network_codec-10000100.log
        date_yyyymmdd: 可选，8 位日期字符串
        subdir: log 下子目录，玩家协议日志为 tag_log
    """
    log_root = Path(run_dir) / server_dir / "log"
    if subdir:
        log_root = log_root / subdir
    d = (date_yyyymmdd or "").strip()
    if d and len(d) == 8 and d.isdigit():
        name = f"{base_filename}.{d}"
    else:
        name = base_filename
    return log_root / name


def read_text_file_best_effort(path: Path, max_bytes: int = 3_145_728) -> Tuple[str, Optional[str]]:
    """读取文本文件，带体积上限。返回 (内容, 错误说明)；错误时内容可能为空。"""
    if not path.exists():
        return "", f"文件不存在: {path}"
    if not path.is_file():
        return "", f"不是普通文件: {path}"
    try:
        size = path.stat().st_size
    except OSError as e:
        return "", str(e)
    if size > max_bytes:
        return "", f"文件过大 ({size} 字节)，上限 {max_bytes}，请缩小范围或改用命令行 tail"
    raw = path.read_bytes()
    for enc in ("utf-8", "utf-8-sig", "gbk", "latin-1"):
        try:
            return raw.decode(enc), None
        except UnicodeDecodeError:
            continue
    return raw.decode("utf-8", errors="replace"), None
