#!/usr/bin/env python3
"""
测试 Markdown 流式渲染性能
用于验证优化效果
"""

import time
import asyncio
from rich.console import Console
from rich.live import Live
from rich.markdown import Markdown

# 模拟流式内容
TEST_CONTENTS = {
    "short": "这是一个简短的测试。\n\n- 列表项 1\n- 列表项 2",
    "medium": """# 中等长度测试

这是一个中等长度的测试文本，包含多个段落。

## 功能特性

- 特性 1: 快速响应
- 特性 2: 流畅渲染
- 特性 3: 美观主题

```python
def hello():
    print("Hello, World!")
```

## 总结

这个测试包含标题、列表和代码块。
""",
    "long": """# 长文本性能测试

## 引言

这是一个较长的测试文本，用于验证流式渲染的性能优化效果。

## 第一部分：文本内容

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

### 代码示例

```python
import asyncio
import time

async def stream_markdown(content: str, delay: float = 0.01):
    \"\"\"模拟流式输出\"\"\"
    words = content.split()
    for word in words:
        yield word + " "
        await asyncio.sleep(delay)
```

```javascript
function streamMarkdown(content, delay = 0.01) {
    // JavaScript 示例
    const words = content.split(' ');
    for (const word of words) {
        yield word + ' ';
        await sleep(delay);
    }
}
```

## 第二部分：更多内容

Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

### 列表

1. 第一项
2. 第二项
3. 第三项

- 无序列表 A
- 无序列表 B
- 无序列表 C

## 第三部分：嵌套结构

> 这是一个引用块
>
> > 这是嵌套引用
>
> 回到第一层

## 结论

通过以上测试，我们可以验证：
1. 自适应节流是否生效
2. 代码块检测是否准确
3. 渲染性能是否提升

测试结束。
"""
}


def simulate_old_approach(content: str, chunk_size: int = 10, chunk_delay: float = 0.005):
    """模拟旧的渲染方式（30ms 固定节流）"""
    console = Console()
    chunks = [content[i:i+chunk_size] for i in range(0, len(content), chunk_size)]

    start_time = time.time()
    update_count = 0
    last_update = 0
    min_interval = 0.03  # 30ms

    buffer = ""
    for chunk in chunks:
        buffer += chunk
        time.sleep(chunk_delay)  # 模拟流式延迟
        current_time = time.time()

        # 固定 30ms 节流
        if current_time - last_update >= min_interval:
            update_count += 1
            last_update = current_time

    end_time = time.time()
    return {
        "duration": end_time - start_time,
        "updates": update_count,
        "avg_interval": (end_time - start_time) / update_count if update_count > 0 else 0
    }


def simulate_new_approach(content: str, chunk_size: int = 10, chunk_delay: float = 0.005):
    """模拟新的渲染方式（自适应节流）"""
    console = Console()
    chunks = [content[i:i+chunk_size] for i in range(0, len(content), chunk_size)]

    start_time = time.time()
    update_count = 0
    last_update = 0
    chunk_count = 0

    buffer = ""
    code_block_open = False

    for chunk in chunks:
        buffer += chunk
        chunk_count += 1
        time.sleep(chunk_delay)  # 模拟流式延迟
        current_time = time.time()

        # 增量代码块检测
        if "```" in chunk:
            new_markers = chunk.count("```")
            code_block_open = code_block_open ^ (new_markers % 2 == 1)

        # 自适应节流
        if chunk_count <= 10:
            min_interval = 0.005  # 5ms
        elif chunk_count <= 50:
            min_interval = 0.01   # 10ms
        else:
            min_interval = 0.015  # 15ms

        if current_time - last_update >= min_interval:
            update_count += 1
            last_update = current_time

    end_time = time.time()
    return {
        "duration": end_time - start_time,
        "updates": update_count,
        "avg_interval": (end_time - start_time) / update_count if update_count > 0 else 0
    }


def run_tests():
    """运行所有测试"""
    console = Console()
    console.print("\n[bold cyan]Markdown 流式渲染性能测试[/bold cyan]\n")

    results = []

    for name, content in TEST_CONTENTS.items():
        console.print(f"[yellow]测试 {name.upper()}[/yellow]")

        # 旧方式
        old_result = simulate_old_approach(content)
        console.print(f"  旧方式: {old_result['updates']} 次更新, 平均间隔 {old_result['avg_interval']*1000:.1f}ms")

        # 新方式
        new_result = simulate_new_approach(content)
        console.print(f"  新方式: {new_result['updates']} 次更新, 平均间隔 {new_result['avg_interval']*1000:.1f}ms")

        # 对比
        improvement = (old_result['avg_interval'] - new_result['avg_interval']) / old_result['avg_interval'] * 100
        console.print(f"  [green]提升: {improvement:.1f}%[/green]\n")

        results.append({
            "name": name,
            "old": old_result,
            "new": new_result,
            "improvement": improvement
        })

    # 总结
    console.print("[bold]性能总结[/bold]")
    avg_improvement = sum(r["improvement"] for r in results) / len(results)
    console.print(f"平均性能提升: [green bold]{avg_improvement:.1f}%[/green bold]")

    # 详细表格
    from rich.table import Table

    table = Table(title="详细对比")
    table.add_column("测试名称", style="cyan")
    table.add_column("旧方式更新次数", style="red")
    table.add_column("新方式更新次数", style="green")
    table.add_column("性能提升", style="yellow")

    for r in results:
        table.add_row(
            r["name"],
            str(r["old"]["updates"]),
            str(r["new"]["updates"]),
            f"{r['improvement']:.1f}%"
        )

    console.print("\n")
    console.print(table)


if __name__ == "__main__":
    run_tests()
