# -*- coding: utf-8 -*-
"""Log-related extended CLI commands."""

from __future__ import annotations

import argparse
from pathlib import Path
from typing import Any

from services.commands import read_text_file_best_effort, resolve_log_file_path
from services.rg_search import rg_search_directory

from .common import add_json_flag, emit_json, is_json_output


def add_logs_subparsers(parent: argparse.ArgumentParser) -> None:
    logs_sub = parent.add_subparsers(dest="logs_command", help="日志命令")

    logs_list = logs_sub.add_parser("list", help="列出服务器日志文件")
    logs_list.add_argument("server")
    logs_list.add_argument("--subdir", default="", help="log 下的子目录，例如 tag_log")
    logs_list.add_argument("--limit", type=int, default=50, help="最多显示文件数")
    add_json_flag(logs_list)

    logs_read = logs_sub.add_parser("read", help="读取服务器日志文件")
    logs_read.add_argument("server")
    logs_read.add_argument("file", help="日志文件名，例如 error.log")
    logs_read.add_argument("--date", help="日期后缀 YYYYMMDD，会读取 file.YYYYMMDD")
    logs_read.add_argument("--subdir", default="", help="log 下的子目录，例如 tag_log")
    logs_read.add_argument("--max-bytes", type=int, default=1_048_576)
    add_json_flag(logs_read)

    logs_search = logs_sub.add_parser("search", help="使用 rg 检索服务器日志目录")
    logs_search.add_argument("server")
    logs_search.add_argument("pattern")
    logs_search.add_argument("--case-sensitive", action="store_true")
    logs_search.add_argument("--regex", action="store_true", help="按正则表达式搜索；默认固定字符串")
    logs_search.add_argument("--word", action="store_true", help="全词匹配")
    logs_search.add_argument("--glob", action="append", help="rg glob 过滤，可重复，例如 --glob *.log")
    logs_search.add_argument("--max-output-chars", type=int, default=20_000)
    add_json_flag(logs_search)


def handle_logs(args: argparse.Namespace, cli: Any) -> None:
    sub = getattr(args, "logs_command", None)
    if not sub:
        raise SystemExit("请指定 logs 子命令：list/read/search")
    if sub == "list":
        _handle_logs_list(args, cli)
    elif sub == "read":
        _handle_logs_read(args, cli)
    elif sub == "search":
        _handle_logs_search(args, cli)


def _handle_logs_list(args: argparse.Namespace, cli: Any) -> None:
    root = Path(cli.run_dir) / args.server / "log"
    if args.subdir:
        root = root / args.subdir
    files = []
    if root.is_dir():
        for item in sorted(root.iterdir(), key=lambda p: p.stat().st_mtime if p.exists() else 0, reverse=True):
            if item.is_file():
                stat = item.stat()
                files.append({"name": item.name, "path": str(item), "size": stat.st_size, "mtime": stat.st_mtime})
                if len(files) >= max(args.limit, 1):
                    break
    data = {"server": args.server, "log_dir": str(root), "files": files}
    if is_json_output(args):
        emit_json(data)
        return
    print(f"日志目录: {root}")
    if not files:
        print("(无日志文件)")
    for item in files:
        print(f"{item['size']:>10}  {item['name']}")


def _handle_logs_read(args: argparse.Namespace, cli: Any) -> None:
    path = resolve_log_file_path(cli.run_dir, args.server, args.file, date_yyyymmdd=args.date, subdir=args.subdir)
    content, err = read_text_file_best_effort(path, max_bytes=max(args.max_bytes, 1024))
    data = {"server": args.server, "path": str(path), "content": content, "error": err}
    if is_json_output(args):
        emit_json(data)
        return
    if err:
        raise SystemExit(err)
    print(content)


def _handle_logs_search(args: argparse.Namespace, cli: Any) -> None:
    root = Path(cli.run_dir) / args.server / "log"
    out, err = rg_search_directory(
        search_root=root,
        pattern=args.pattern,
        case_sensitive=args.case_sensitive,
        use_regex=args.regex,
        whole_word=args.word,
        glob_globs=args.glob,
    )
    max_chars = max(args.max_output_chars, 1000)
    if len(out) > max_chars:
        out = out[:max_chars] + f"\n... <truncated {len(out) - max_chars} chars>"
    data = {"server": args.server, "search_root": str(root), "matches": out, "error": err}
    if is_json_output(args):
        emit_json(data)
        return
    if err:
        raise SystemExit(err)
    print(out)
