#!/usr/bin/env python3
"""
生成 easyclaw 模拟日志，用于测试监控脚本。

用法：
  python generate_demo_log.py [输出文件路径] [天数]

示例：
  python generate_demo_log.py easyclaw.log 3
"""

import random
import sys
from datetime import datetime, timedelta

URLS = [
    "https://example.com/products/page1",
    "https://example.com/products/page2",
    "https://example.com/products/page3",
    "https://shop.example.com/items/123",
    "https://shop.example.com/items/456",
    "https://shop.example.com/items/789",
    "https://api.example.com/data/feed",
    "https://api.example.com/data/list",
    "https://news.example.com/article/001",
    "https://news.example.com/article/002",
]

ERROR_MSGS = [
    "Timeout fetching {url}",
    "HTTP 403 Forbidden: {url}",
    "HTTP 500 Internal Server Error: {url}",
    "Connection refused: {url}",
    "SSL certificate verify failed: {url}",
]


def generate_log(output_path: str, days: int = 3):
    now = datetime.now()
    start = now - timedelta(days=days)
    current = start
    lines = []

    while current < now:
        url = random.choice(URLS)

        # 模拟一次抓取任务
        lines.append(f"{current.strftime('%Y-%m-%d %H:%M:%S')} [INFO] Task started: fetch {url}")
        current += timedelta(seconds=random.randint(1, 3))

        roll = random.random()
        if roll < 0.75:
            # 成功
            data_size = random.randint(512, 65536)
            lines.append(f"{current.strftime('%Y-%m-%d %H:%M:%S')} [SUCCESS] Fetched {data_size} bytes from {url}")
        elif roll < 0.90:
            # 警告 + 重试后成功
            lines.append(f"{current.strftime('%Y-%m-%d %H:%M:%S')} [WARNING] Retry 1/3 for {url}")
            current += timedelta(seconds=random.randint(2, 5))
            data_size = random.randint(512, 65536)
            lines.append(f"{current.strftime('%Y-%m-%d %H:%M:%S')} [SUCCESS] Fetched {data_size} bytes from {url}")
        else:
            # 失败
            err = random.choice(ERROR_MSGS).format(url=url)
            lines.append(f"{current.strftime('%Y-%m-%d %H:%M:%S')} [ERROR] {err}")

        # 间隔
        current += timedelta(seconds=random.randint(5, 60))

    with open(output_path, "w", encoding="utf-8") as f:
        f.write("\n".join(lines) + "\n")

    print(f"已生成 {len(lines)} 条模拟日志 -> {output_path}")


if __name__ == "__main__":
    path = sys.argv[1] if len(sys.argv) > 1 else "easyclaw.log"
    days = int(sys.argv[2]) if len(sys.argv) > 2 else 3
    generate_log(path, days)
