import argparse
import json
import sys
import os

# 确保能导入本地模块
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)

from config import DocLintConfig
from engine import DocLintEngine


def main(args=None):
    """
        CLI 入口函数
        :param args: 参数列表，默认为 sys.argv[1:]
        """
    if args is None:
        args = sys.argv[1:]

    parser = argparse.ArgumentParser(description="DocLint - 文档规范检查工具")
    parser.add_argument("files", nargs="+", help="要检查的文件路径")
    parser.add_argument("--config", default=".stylecheckrrc.yaml", help="配置文件路径")
    parser.add_argument("--output", default="-", help="输出文件路径")
    parser.add_argument("--verbose", "-v", action="store_true", help="显示详细信息")
    parsed_args = parser.parse_args(args)

    # 1. 加载配置
    config = DocLintConfig(config_path=parsed_args.config)

    if parsed_args.verbose:
        print(f"[CONFIG] 配置文件：{config.config_path}")
        print(f"[CONFIG] 启用规则：{config.get_all_enabled_rules()}")
        print(f"[CONFIG] 忽略模式：{config.ignore_patterns}")

    # 2. 初始化引擎
    engine = DocLintEngine(config=config)

    if parsed_args.verbose:
        stats = engine.get_rule_stats()
        print(f"[ENGINE] {stats}")

    # 3. 执行检查
    diagnostics = engine.check_files(parsed_args.files)

    # 4. 输出结果
    output_data = {
        "version": "1.0",
        "config": {
            "file": config.config_path,
            "enabled_rules": config.get_all_enabled_rules()
        },
        "diagnostics": [d.to_dict() for d in diagnostics],
        "summary": {
            "total_files": len(parsed_args.files),
            "total_issues": len(diagnostics),
            "errors": len([d for d in diagnostics if d.severity == "error"]),
            "warnings": len([d for d in diagnostics if d.severity == "warning"])
        }
    }

    output_json = json.dumps(output_data, indent=2, ensure_ascii=False)

    if parsed_args.output == "-":
        print(output_json)
    else:
        with open(parsed_args.output, 'w', encoding='utf-8') as f:
            f.write(output_json)
        if parsed_args.verbose:
            print(f"[OUTPUT] 结果已写入：{parsed_args.output}")

    # 始终返回 0，确保 CI 不阻断
    return 0


if __name__ == "__main__":
    sys.exit(main())
