"""
日志管理 API 路由
"""
import os
import sys
import logging
import yaml
from datetime import datetime
from logging.handlers import TimedRotatingFileHandler, RotatingFileHandler
from flask import Blueprint, request, jsonify

# 获取项目根目录
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, PROJECT_ROOT)

# 加载配置
CONFIG_PATH = os.path.join(PROJECT_ROOT, 'config.yaml')
with open(CONFIG_PATH, 'r', encoding='utf-8') as f:
    CONFIG = yaml.safe_load(f)

# 日志目录
LOG_BASE_DIR = os.path.join(PROJECT_ROOT, 'logs')

# 创建蓝图
logs_bp = Blueprint('logs', __name__, url_prefix='/api')


def setup_logs_logger():
    """配置日志系统，按日期分目录存储"""
    today = datetime.now().strftime('%Y-%m-%d')
    log_dir = os.path.join(LOG_BASE_DIR, today)
    os.makedirs(log_dir, exist_ok=True)

    logger = logging.getLogger('logs_api')
    logger.setLevel(logging.DEBUG)
    logger.handlers.clear()

    # 全部日志处理器
    all_log_path = os.path.join(log_dir, 'all.log')
    all_handler = TimedRotatingFileHandler(all_log_path, when='midnight', interval=1, backupCount=30, encoding='utf-8')
    all_handler.setLevel(logging.DEBUG)
    all_handler.setFormatter(logging.Formatter(
        '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
        datefmt='%Y-%m-%d %H:%M:%S'
    ))

    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(logging.Formatter(
        '[%(asctime)s] %(levelname)s: %(message)s',
        datefmt='%H:%M:%S'
    ))

    logger.addHandler(all_handler)
    logger.addHandler(console_handler)

    return logger


logs_logger = setup_logs_logger()


@logs_bp.route('/web-log', methods=['POST'])
def receive_web_log():
    """接收前端页面发送的日志"""
    data = request.json
    level = data.get('level', 'info')
    message = data.get('message', '')
    page = data.get('page', 'unknown')
    timestamp = data.get('timestamp', datetime.now().isoformat())

    log_message = f'[WEB-{page}] {message}'

    if level == 'error':
        logs_logger.error(log_message)
    elif level == 'warning':
        logs_logger.warning(log_message)
    elif level == 'debug':
        logs_logger.debug(log_message)
    else:
        logs_logger.info(log_message)

    return jsonify({'code': 0, 'message': '日志接收成功'})


def format_file_size(size_bytes):
    """格式化文件大小"""
    if size_bytes < 1024:
        return f'{size_bytes} B'
    elif size_bytes < 1024 * 1024:
        return f'{size_bytes / 1024:.1f} KB'
    else:
        return f'{size_bytes / (1024 * 1024):.1f} MB'


@logs_bp.route('/log-files', methods=['GET'])
def get_log_files():
    """获取指定日期的日志文件列表"""
    date = request.args.get('date')
    if not date:
        return jsonify({'code': 1, 'message': '缺少日期参数'})

    # 验证日期格式
    try:
        datetime.strptime(date, '%Y-%m-%d')
    except ValueError:
        return jsonify({'code': 1, 'message': '日期格式错误，应为 YYYY-MM-DD'})

    log_dir = os.path.join(LOG_BASE_DIR, date)

    if not os.path.exists(log_dir):
        return jsonify({'code': 0, 'data': []})

    log_files = []
    file_names = ['all.log', 'error.log', 'request.log']

    for file_name in file_names:
        file_path = os.path.join(log_dir, file_name)
        if os.path.exists(file_path):
            size = os.path.getsize(file_path)
            log_files.append({
                'name': file_name.replace('.log', ''),
                'file': f'{date}/{file_name}',
                'size': format_file_size(size)
            })

    return jsonify({'code': 0, 'data': log_files})


@logs_bp.route('/log-content', methods=['GET'])
def get_log_content():
    """获取日志文件内容"""
    file_path = request.args.get('file')
    if not file_path:
        return jsonify({'code': 1, 'message': '缺少文件参数'})

    # 防止目录遍历攻击
    file_path = file_path.replace('..', '').replace('//', '/')
    full_path = os.path.join(LOG_BASE_DIR, file_path)

    # 验证文件路径是否在日志目录下
    if not full_path.startswith(LOG_BASE_DIR):
        return jsonify({'code': 1, 'message': '无效的文件路径'})

    if not os.path.exists(full_path) or not os.path.isfile(full_path):
        return jsonify({'code': 1, 'message': '日志文件不存在'})

    try:
        size = os.path.getsize(full_path)
        # 限制读取大小，最大 5MB
        max_size = 5 * 1024 * 1024
        if size > max_size:
            with open(full_path, 'r', encoding='utf-8') as f:
                f.seek(size - max_size)
                content = '... (日志文件较大，已显示最后 5MB 内容) ...\n\n' + f.read()
        else:
            with open(full_path, 'r', encoding='utf-8') as f:
                content = f.read()

        return jsonify({
            'code': 0,
            'data': {
                'file': os.path.basename(file_path),
                'path': file_path,
                'size': format_file_size(size),
                'content': content
            }
        })
    except Exception as e:
        return jsonify({'code': 1, 'message': f'读取日志文件失败: {str(e)}'})


# ============ 训练日志相关 API ============

# 训练日志保存在 logs/{日期} 目录下
TRAINING_LOGS_BASE_DIR = '/app/base/logs'
# 本地开发时的备用路径（Windows）
LOCAL_TRAINING_LOGS_BASE_DIR = os.path.join(PROJECT_ROOT, 'logs')

# 添加调试日志
logs_logger.info(f"[DEBUG] TRAINING_LOGS_BASE_DIR: {TRAINING_LOGS_BASE_DIR}")
logs_logger.info(f"[DEBUG] LOCAL_TRAINING_LOGS_BASE_DIR: {LOCAL_TRAINING_LOGS_BASE_DIR}")


@logs_bp.route('/training-log-files', methods=['GET'])
def get_training_log_files():
    """获取训练日志文件列表 - 从 logs/{日期} 目录下的 .log 文件"""
    try:
        # 确定基础目录
        logs_base_dir = TRAINING_LOGS_BASE_DIR
        if not os.path.exists(logs_base_dir):
            logs_base_dir = LOCAL_TRAINING_LOGS_BASE_DIR

        logs_logger.info(f"[DEBUG] logs_base_dir: {logs_base_dir}, exists: {os.path.exists(logs_base_dir)}")

        if not os.path.exists(logs_base_dir):
            return jsonify({'code': 0, 'data': []})

        # 遍历所有日期目录，收集训练日志文件
        log_files = []
        date_dirs = []

        try:
            # 获取所有日期目录（格式: YYYY-MM-DD）
            for item in os.listdir(logs_base_dir):
                item_path = os.path.join(logs_base_dir, item)
                if os.path.isdir(item_path):
                    # 验证是否为日期目录
                    try:
                        datetime.strptime(item, '%Y-%m-%d')
                        date_dirs.append(item)
                    except ValueError:
                        pass
        except Exception as list_err:
            logs_logger.error(f"[DEBUG] Failed to list base directory: {list_err}")
            return jsonify({'code': 0, 'data': []})

        # 按日期排序（最新的在前面）
        date_dirs.sort(reverse=True)

        logs_logger.info(f"[DEBUG] Date directories: {date_dirs}")

        # 遍历每个日期目录，查找 .log 文件
        for date_dir in date_dirs:
            date_full_path = os.path.join(logs_base_dir, date_dir)
            try:
                files = os.listdir(date_full_path)
            except Exception as list_err:
                logs_logger.warning(f"[DEBUG] Failed to list {date_full_path}: {list_err}")
                continue

            for file_name in files:
                if not file_name.endswith('.log'):
                    continue

                file_path = os.path.join(date_full_path, file_name)
                try:
                    size = os.path.getsize(file_path)
                except Exception as size_err:
                    logs_logger.warning(f"[DEBUG] Failed to get size of {file_path}: {size_err}")
                    continue

                # 文件名格式: {task_id}_{task_name}.log
                # 例如: 889_testing.log
                parts = file_name.replace('.log', '').split('_', 1)
                if len(parts) >= 2:
                    task_id = parts[0]
                    task_name = parts[1]
                    try:
                        dt = datetime.strptime(date_dir, '%Y-%m-%d')
                        # 使用日期目录的时间作为排序键
                        sort_key = dt.timestamp()
                        display_date = date_dir
                    except:
                        sort_key = 0
                        display_date = date_dir
                else:
                    task_id = 'unknown'
                    task_name = file_name.replace('.log', '')
                    sort_key = 0
                    display_date = date_dir

                # 构建相对路径 (日期/文件名)
                relative_path = f"{date_dir}/{file_name}"

                log_files.append({
                    'name': task_name,
                    'file': relative_path,
                    'task_id': task_id,
                    'date': display_date,
                    'size': format_file_size(size),
                    'sort_key': sort_key
                })

        # 按时间戳排序（最新的在前面）
        log_files.sort(key=lambda x: x['sort_key'] if x['sort_key'] else 0, reverse=True)

        logs_logger.info(f"[DEBUG] Found {len(log_files)} training log files")

        return jsonify({'code': 0, 'data': log_files})
    except Exception as e:
        logs_logger.error(f"[DEBUG] 获取训练日志列表失败: {e}")
        return jsonify({'code': 1, 'message': f'获取训练日志列表失败: {str(e)}'})


@logs_bp.route('/training-log-content', methods=['GET'])
def get_training_log_content():
    """获取训练日志文件内容 - 从 logs/{日期}/ 目录"""
    file_name = request.args.get('file')
    if not file_name:
        return jsonify({'code': 1, 'message': '缺少文件参数'})

    logs_logger.info(f"[DEBUG] ============ get_training_log_content ============")
    logs_logger.info(f"[DEBUG] file: {file_name}")

    # 防止目录遍历攻击
    file_name = file_name.replace('..', '').replace('//', '/')

    # file 格式: 日期/文件名，例如: 2026-01-28/889_testing.log
    # 解析日期和文件名
    parts = file_name.split('/')
    if len(parts) < 2:
        return jsonify({'code': 1, 'message': '无效的文件路径格式'})

    date_dir = parts[0]
    log_file_name = '/'.join(parts[1:])

    # 验证日期格式
    try:
        datetime.strptime(date_dir, '%Y-%m-%d')
    except ValueError:
        return jsonify({'code': 1, 'message': '无效的日期格式'})

    # 确定基础目录
    container_base_dir = TRAINING_LOGS_BASE_DIR  # /app/base/logs
    local_base_dir = LOCAL_TRAINING_LOGS_BASE_DIR  # 项目目录下的 logs

    container_full_path = os.path.join(container_base_dir, date_dir, log_file_name)
    local_full_path = os.path.join(local_base_dir, date_dir, log_file_name)

    logs_logger.info(f"[DEBUG] container_base_dir: {container_base_dir}, exists: {os.path.exists(container_base_dir)}")
    logs_logger.info(f"[DEBUG] local_base_dir: {local_base_dir}, exists: {os.path.exists(local_base_dir)}")
    logs_logger.info(f"[DEBUG] container_full_path: {container_full_path}, exists: {os.path.exists(container_full_path)}")
    logs_logger.info(f"[DEBUG] local_full_path: {local_full_path}, exists: {os.path.exists(local_full_path)}")

    # 选择最终路径
    full_path = None
    if os.path.exists(container_full_path):
        full_path = container_full_path
        logs_logger.info(f"[DEBUG] Using container path")
    elif os.path.exists(local_full_path):
        full_path = local_full_path
        logs_logger.info(f"[DEBUG] Using local path")
    else:
        logs_logger.error(f"[DEBUG] File not found: {file_name}")
        return jsonify({'code': 1, 'message': f'日志文件不存在: {file_name}'})

    logs_logger.info(f"[DEBUG] Final full_path: {full_path}")

    # 尝试直接读取文件
    try:
        max_size = 10 * 1024 * 1024
        content = ''
        read_success = False

        try:
            with open(full_path, 'rb') as f:
                f.seek(0, 2)
                size = f.tell()
                f.seek(0)

                if size > max_size:
                    f.seek(size - max_size)
                    content = '... (日志文件较大，已显示最后 10MB 内容) ...\n\n' + f.read().decode('utf-8', errors='ignore')
                else:
                    content = f.read().decode('utf-8', errors='ignore')
            read_success = True
        except (PermissionError, OSError) as pe:
            logs_logger.warning(f"[DEBUG] 直接读取失败: {pe}，尝试共享模式读取")
            import mmap
            try:
                with open(full_path, 'rb') as f:
                    mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
                    try:
                        f.seek(0, 2)
                        size = f.tell()
                        if size > max_size:
                            content = '... (日志文件较大，已显示最后 10MB 内容) ...\n\n' + \
                                mm[-max_size:].decode('utf-8', errors='ignore')
                        else:
                            content = mm[:].decode('utf-8', errors='ignore')
                        read_success = True
                    finally:
                        mm.close()
            except Exception as e2:
                logs_logger.error(f"[DEBUG] 共享模式读取失败: {e2}")
                return jsonify({
                    'code': 2,
                    'message': f'日志文件正在被训练进程占用，训练结束后可查看完整内容',
                    'data': {
                        'file': log_file_name,
                        'size': format_file_size(0),
                        'content': ''
                    }
                })

        if read_success:
            return jsonify({
                'code': 0,
                'data': {
                    'file': log_file_name,
                    'size': format_file_size(size),
                    'content': content
                }
            })
    except Exception as e:
        logs_logger.error(f"[DEBUG] 读取日志文件失败: {e}")
        return jsonify({'code': 1, 'message': f'读取日志文件失败: {str(e)}'})
