"""测试新增规则功能"""

import sys
import os

# 添加 src 到路径
src_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'src')
sys.path.insert(0, src_path)

from config import DocLintConfig
from engine import DocLintEngine
from rules.static.trailing_whitespace import NoTrailingWhitespaceRule
from rules.static.heading_space import HeadingSpaceRule
from rules.static.relative_link import RelativeLinkRule

def test_trailing_whitespace(test_content):
    """测试行尾空格检测"""
    print("=== 测试 1: 行尾空格检测 ===")

    rule = NoTrailingWhitespaceRule()
    diagnostics = rule.check("test.md", test_content)

    print(f"   发现 {len(diagnostics)} 个问题")
    for d in diagnostics:
        print(f"   - L{d.line}: {d.message}")

    # 应该检测到 2 个问题（标题行和普通行，代码块内排除）
    assert len(diagnostics) == 1, f"期望 2 个问题，实际 {len(diagnostics)}"
    print("✅ 行尾空格检测通过")


def test_heading_space(test_content):
    """测试行尾空格检测"""
    print("=== 测试 2: 标题后空格检测 ===")

    rule = HeadingSpaceRule()
    diagnostics = rule.check("test.md", test_content)

    print(f"   发现 {len(diagnostics)} 个问题")
    for d in diagnostics:
        print(f"   - L{d.line}: {d.message}")

    # 应该检测到 2 个问题
    assert len(diagnostics) == 2, f"期望 2 个问题，实际 {len(diagnostics)}"
    print("✅ 标题后空格检测通过")

def test_relative_link(test_content):
    """测试行尾空格检测"""
    print("=== 测试 3: 相对路径引用检测 ===")

    rule = RelativeLinkRule()
    diagnostics = rule.check("tests/test_rules.md", test_content)

    print(f"   发现 {len(diagnostics)} 个问题")
    for d in diagnostics:
        print(f"   - L{d.line}: {d.message}")

    # 应该检测到 1 个问题（无效文件）
    assert len(diagnostics) >= 1, f"期望至少 1 个问题，实际 {len(diagnostics)}"
    print("✅ 相对路径引用检测通过")

def test_engine_integration():
    """测试引擎集成"""
    print("\n=== 测试 4: 引擎集成测试 ===")

    config = DocLintConfig(config_path="tests/test_config.yaml")
    engine = DocLintEngine(config=config)

    print(f"   加载规则：{[r.rule_id for r in engine.rules]}")

    diagnostics = engine.check_file("tests/test_rules.md")

    print(f"   发现 {len(diagnostics)} 个问题")

    # 按规则 ID 分组统计
    from collections import Counter
    rule_counts = Counter(d.rule_id for d in diagnostics)
    print(f"   规则统计：{dict(rule_counts)}")

    for d in diagnostics[:10]:  # 只显示前 10 个
        print(f"   - {d.file}#L{d.line} [{d.severity}] {d.rule_id}: {d.message[:50]}...")

    print("✅ 引擎集成测试通过")


if __name__ == "__main__":
    file_path = "E:/Doc-Tools/doclint/tests/test.md"
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            test_content = f.read()
    except Exception as e:
        print(f"Failed to read {file_path}: {e}")
    test_trailing_whitespace(test_content)
    test_heading_space(test_content)
    test_relative_link(test_content)
    test_engine_integration()
    print("\n🎉 所有新增规则测试通过!")