#!/usr/bin/env python3
"""
NexusTools benchmark dataset generator.

Generates a deterministic synthetic Nginx/Apache-style access log of a target
size (default 250 MiB). The same seed always produces byte-identical output, so
independent reviewers can reproduce the exact file used in the published
benchmark tables.

Usage:
    python generate_250mb_log.py --output access_250mb.log --size-mb 250
    python generate_250mb_log.py --output access_250mb.log --size-mb 250 --seed 20261120

After generation, compute the SHA-256 digest and compare it with the value
published in https://nexustools.tech/benchmarks/ .
"""

import argparse
import hashlib
import random
import sys
from pathlib import Path

METHODS = ["GET", "GET", "GET", "POST", "PUT", "DELETE"]
PATHS = [
    "/api/v1/orders",
    "/api/v1/users",
    "/api/v1/products",
    "/api/v1/checkout",
    "/healthz",
    "/metrics",
    "/static/app.js",
    "/static/style.css",
]
STATUSES = [200, 200, 200, 200, 201, 204, 301, 304, 400, 401, 403, 404, 500, 502, 503]
USER_AGENTS = [
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "curl/8.5.0",
    "kube-probe/1.29",
    "Go-http-client/2.0",
]

TARGET_BYTES_DEFAULT = 250 * 1024 * 1024
DEFAULT_SEED = 20261120


def build_line(rng: random.Random, line_no: int) -> str:
    day = 1 + (line_no // 86400) % 27
    hour = (line_no // 3600) % 24
    minute = (line_no // 60) % 60
    second = line_no % 60
    ip = f"10.{rng.randint(0, 255)}.{rng.randint(0, 255)}.{rng.randint(1, 254)}"
    method = rng.choice(METHODS)
    path = rng.choice(PATHS)
    status = rng.choice(STATUSES)
    size = rng.randint(120, 48000)
    ua = rng.choice(USER_AGENTS)
    return (
        f'{ip} - - [{"%02d" % day}/Nov/2026:{hour:02d}:{minute:02d}:{second:02d} +0000] '
        f'"{method} {path} HTTP/1.1" {status} {size} "-" "{ua}"\n'
    )


def generate(output: Path, target_bytes: int, seed: int) -> tuple[int, str, str]:
    rng = random.Random(seed)
    digest = hashlib.sha256()
    written = 0
    lines = 0
    with output.open("w", encoding="utf-8", newline="\n") as handle:
        while written < target_bytes:
            line = build_line(rng, lines)
            encoded = line.encode("utf-8")
            handle.write(line)
            digest.update(encoded)
            written += len(encoded)
            lines += 1
    return lines, digest.hexdigest(), str(output)


def main() -> int:
    parser = argparse.ArgumentParser(description="Generate a deterministic synthetic access log for NexusTools benchmarks.")
    parser.add_argument("--output", default="access_250mb.log", help="Output file path (default: access_250mb.log)")
    parser.add_argument("--size-mb", type=int, default=250, help="Target file size in MiB (default: 250)")
    parser.add_argument("--seed", type=int, default=DEFAULT_SEED, help=f"Random seed (default: {DEFAULT_SEED})")
    args = parser.parse_args()

    if args.size_mb <= 0:
        print("error: --size-mb must be positive", file=sys.stderr)
        return 2

    output = Path(args.output)
    target_bytes = args.size_mb * 1024 * 1024
    lines, sha256, path = generate(output, target_bytes, args.seed)

    print(f"Generated: {path}")
    print(f"Lines:     {lines:,}")
    print(f"Size:      {output.stat().st_size / (1024 * 1024):.2f} MiB")
    print(f"Seed:      {args.seed}")
    print(f"SHA-256:   {sha256}")
    print("")
    print("Compare the SHA-256 digest with the dataset fingerprint published at")
    print("https://nexustools.tech/benchmarks/ (section: Dataset & Reproduction).")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
