"""QuizTrainer CLI 命令行入口.

用法:
    quiztrainer web                    # 启动 Web 服务 (调试模式)
    quiztrainer web --production       # 生产模式运行
    quiztrainer web -p 8080            # 指定端口
    quiztrainer web --host 0.0.0.0     # 指定主机地址
    quiztrainer list                   # 列出所有题库
    quiztrainer stats                  # 显示统计信息
    quiztrainer import <file>          # 导入 JSON 题库
    quiztrainer import-word <file>     # 从 Word 文档导入题库
    quiztrainer import-word --preview  # 预览 Word 文档内容
"""

from __future__ import annotations

import argparse
import json
import sys
import webbrowser
from pathlib import Path

from .core import DataManager, QuizManager
from .tools.word_importer import ParsedQuestion, QuestionParseResult


def _build_parser() -> argparse.ArgumentParser:
    """构建命令行参数解析器."""
    parser = argparse.ArgumentParser(
        prog="quiztrainer",
        description="QuizTrainer - 在线答题训练系统",
    )
    parser.add_argument(
        "-v",
        "--version",
        action="version",
        version="%(prog)s 0.1.0",
    )

    subparsers = parser.add_subparsers(dest="command", help="子命令")

    # web 子命令
    web_parser = subparsers.add_parser("web", help="启动 Web 服务")
    web_parser.add_argument(
        "-p",
        "--port",
        type=int,
        default=5000,
        help="Web 服务端口 (默认: 5000)",
    )
    web_parser.add_argument(
        "--no-open",
        action="store_true",
        dest="no_open",
        help="不自动打开浏览器",
    )
    web_parser.add_argument(
        "--debug",
        action="store_true",
        help="启用调试模式",
    )
    web_parser.add_argument(
        "--production",
        action="store_true",
        dest="production",
        help="生产模式运行 (禁用调试,允许外部访问)",
    )
    web_parser.add_argument(
        "--host",
        type=str,
        default="127.0.0.1",
        help="绑定主机地址 (默认: 127.0.0.1)",
    )

    # list 子命令
    list_parser = subparsers.add_parser("list", help="列出所有题库")
    list_parser.add_argument(
        "--json",
        action="store_true",
        help="以 JSON 格式输出",
    )

    # stats 子命令
    stats_parser = subparsers.add_parser("stats", help="显示统计信息")
    stats_parser.add_argument(
        "--json",
        action="store_true",
        help="以 JSON 格式输出",
    )

    # add 子命令
    add_parser = subparsers.add_parser("add", help="添加题目")
    add_parser.add_argument("bank", help="题库名称")
    add_parser.add_argument("--type", "-t", default="choice", help="题目类型")
    add_parser.add_argument("--question", "-q", required=True, help="题目内容")
    add_parser.add_argument("--answer", "-a", required=True, help="正确答案")
    add_parser.add_argument("--category", "-c", default="默认分类", help="题目分类")
    add_parser.add_argument("--difficulty", "-d", default="medium", help="难度")
    add_parser.add_argument("--explanation", "-e", default="", help="解析")
    add_parser.add_argument("--options", nargs="*", help="选项列表")

    # import 子命令 (JSON)
    import_parser = subparsers.add_parser("import", help="导入 JSON 题库")
    import_parser.add_argument("file", type=Path, help="题库文件路径 (.json)")

    # import-word 子命令
    word_parser = subparsers.add_parser("import-word", help="从 Word 文档导入题库")
    word_parser.add_argument("file", type=Path, help="Word 文件路径 (.docx)")
    word_parser.add_argument(
        "--bank",
        "-b",
        default=None,
        help="题库名称 (默认: 文件名)",
    )
    word_parser.add_argument(
        "--preview",
        "-p",
        action="store_true",
        help="仅预览,不导入",
    )
    word_parser.add_argument(
        "--max-preview",
        "-m",
        type=int,
        default=10,
        help="预览最大题目数 (默认: 10)",
    )
    word_parser.add_argument(
        "--category",
        "-c",
        default="默认分类",
        help="题库分类 (默认: 默认分类)",
    )
    word_parser.add_argument(
        "--difficulty",
        "-d",
        default="medium",
        choices=["easy", "medium", "hard"],
        help="默认难度 (默认: medium)",
    )

    # export 子命令
    export_parser = subparsers.add_parser("export", help="导出题库")
    export_parser.add_argument("bank", help="题库名称")
    export_parser.add_argument("output", type=Path, help="输出文件路径")

    return parser


def _print_question(q: ParsedQuestion, index: int) -> None:
    """打印单个题目."""
    if q.options:
        for i, _opt in enumerate(q.options):
            ["A", "B", "C", "D", "E", "F"][i]

    if q.explanation:
        pass


def _print_result(result: QuestionParseResult) -> None:
    """打印解析结果."""
    # 打印成功的题目
    if result.success:
        for i, q in enumerate(result.success[:10]):
            _print_question(q, i)

        if len(result.success) > 10:
            pass


def _cmd_web(args: argparse.Namespace) -> None:
    """启动 Web 服务."""
    import os

    from .app import create_app

    app = create_app()

    # 设置运行参数
    debug_mode = args.debug or False
    is_production = args.production or False

    # 生产模式覆盖调试模式
    if is_production:
        debug_mode = False

    # 设置主机
    host = args.host
    port = args.port

    # 设置环境变量
    os.environ["QUIZTRAINER_DEBUG"] = str(debug_mode).lower()
    os.environ["QUIZTRAINER_HOST"] = host
    os.environ["QUIZTRAINER_PORT"] = str(port)

    # 自动打开浏览器
    if not args.no_open and not is_production:
        url = f"http://{host}:{port}"
        webbrowser.open(url)

    if is_production:
        pass

    app.run(debug=debug_mode, host=host, port=port)


def _cmd_list(args: argparse.Namespace) -> None:
    """列出所有题库."""
    data_manager = DataManager()

    banks = data_manager.get_question_banks()
    categories = data_manager.get_categories()

    if args.json:
        {
            "banks": banks,
            "categories": [{"name": c.name, "count": c.question_count} for c in categories],
        }
    else:
        for _bank in banks:
            pass

        for _cat in categories:
            pass


def _cmd_stats(args: argparse.Namespace) -> None:
    """显示统计信息."""
    quiz_manager = QuizManager()
    stats = quiz_manager.get_statistics()

    if args.json:
        pass
    elif stats["category_stats"]:
        for stat in stats["category_stats"].values():
            stat["correct"] / stat["total"] * 100 if stat["total"] > 0 else 0


def _cmd_add(args: argparse.Namespace) -> None:
    """添加题目."""
    data_manager = DataManager()
    quiz_manager = QuizManager(data_manager)

    question = quiz_manager.create_question(
        q_type=args.type,
        question=args.question,
        answer=args.answer,
        category=args.category,
        difficulty=args.difficulty,
        explanation=args.explanation,
        options=args.options,
    )

    data_manager.add_question(question, args.bank)


def _cmd_import(args: argparse.Namespace) -> None:
    """导入 JSON 题库."""
    data_manager = DataManager()

    if not args.file.exists():
        sys.exit(1)

    try:
        with args.file.open("r", encoding="utf-8") as f:
            data = json.load(f)
    except json.JSONDecodeError:
        sys.exit(1)

    # 获取题库名称
    bank_name = args.file.stem

    # 导入题目
    from .models import BaseQuestion

    questions = [BaseQuestion.from_dict(q) for q in data]
    data_manager.save_question_bank(bank_name, questions)


def _cmd_import_word(args: argparse.Namespace) -> None:
    """从 Word 文档导入题库."""
    from .tools.word_importer import WordImporter

    if not args.file.exists():
        sys.exit(1)

    if args.file.suffix.lower() not in {".docx", ".doc"}:
        sys.exit(1)

    # 检查依赖
    try:
        importer = WordImporter(args.file)
    except ImportError:
        sys.exit(1)

    # 解析文档

    result = importer.parse_preview(args.max_preview) if args.preview else importer.parse()

    # 打印结果
    _print_result(result)

    # 如果不是预览模式,保存到题库
    if not args.preview and result.success:
        bank_name = args.bank or args.file.stem

        # 设置默认分类和难度
        for q in result.success:
            if not q.category or q.category == "默认分类":
                q.category = args.category
            if q.difficulty == "medium":
                q.difficulty = args.difficulty

        importer.save_to_bank(result, bank_name)


def _cmd_export(args: argparse.Namespace) -> None:
    """导出题库."""
    data_manager = DataManager()
    questions = data_manager.load_question_bank(args.bank)

    if not questions:
        sys.exit(1)

    data = [q.to_dict() for q in questions]

    with args.output.open("w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)


def main(argv: list[str] | None = None) -> None:
    """CLI 主入口."""
    parser = _build_parser()
    args = parser.parse_args(argv)

    if not args.command:
        parser.print_help()
        sys.exit(1)

    # 根据子命令执行对应函数
    commands = {
        "web": _cmd_web,
        "list": _cmd_list,
        "stats": _cmd_stats,
        "add": _cmd_add,
        "import": _cmd_import,
        "import-word": _cmd_import_word,
        "export": _cmd_export,
    }

    if args.command in commands:
        commands[args.command](args)
    else:
        parser.print_help()
        sys.exit(1)


if __name__ == "__main__":
    main()
