#!/usr/bin/env python3
"""Continuously submit diversified demo workloads until interrupted."""

from __future__ import annotations

import argparse
import time

from polyform_backend.simulator import Experiment, run_experiment


FAULTS = (
    "locate_end_of_central_directory.faulty_short_comment",
    "normalize_extraction_path.faulty_depth_limit",
)


def experiment_for_batch(batch: int, clients: int, runs: int) -> Experiment:
    """Give each batch fresh client identities and balanced new compositions."""
    return Experiment(
        clients=clients,
        runs_per_client=runs,
        mode="diversified",
        strategy="balanced",
        bad=FAULTS,
        seed=10_000 + batch,
    )


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--url", default="http://127.0.0.1:8000")
    parser.add_argument("--release", type=int, required=True)
    parser.add_argument("--clients-per-batch", type=int, default=24)
    parser.add_argument("--runs-per-client", type=int, default=1)
    parser.add_argument("--interval", type=float, default=4.0)
    parser.add_argument("--max-batches", type=int)
    args = parser.parse_args()

    batch = 0
    try:
        while args.max_batches is None or batch < args.max_batches:
            batch += 1
            result = run_experiment(
                args.url,
                args.release,
                experiment_for_batch(batch, args.clients_per_batch, args.runs_per_client),
            )
            healthy = 1 - result["failures"] / result["executions"]
            print(
                f"batch={batch} clients={result['clients']} "
                f"executions={result['executions']} healthy={healthy:.1%}",
                flush=True,
            )
            if args.max_batches is None or batch < args.max_batches:
                time.sleep(max(args.interval, 0.1))
    except KeyboardInterrupt:
        pass
    return 0


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