from __future__ import annotations

from dataclasses import dataclass
import time
from typing import Any, Sequence


@dataclass
class Throughput:
    started_at: float
    last_report_at: float
    total: int


def start_throughput() -> Throughput:
    now = time.monotonic()
    return Throughput(started_at=now, last_report_at=now, total=0)


def maybe_report(
    t: Throughput,
    *,
    label: str,
    every_seconds: float = 5.0,
) -> str | None:
    now = time.monotonic()
    if now - t.last_report_at < every_seconds:
        return None

    elapsed = max(1e-9, now - t.started_at)
    rate = t.total / elapsed
    t.last_report_at = now
    return f"{label}: total={t.total} rate={rate:,.0f} rec/s elapsed={elapsed:,.1f}s"


# ---------------------------------------------------------------------------
# Enhanced summary stats (used by CLI after a run)
# ---------------------------------------------------------------------------

def format_summary(results: Sequence[Any], *, wall_seconds: float) -> str:
    """Return a multi-line pretty summary of a completed run.

    *results* is a sequence of :class:`WorkerResult` (or any object with
    ``worker_id``, ``records``, ``errors``, ``elapsed_seconds``).
    """

    lines: list[str] = []
    total_records = 0
    total_errors = 0
    max_rate = 0.0

    lines.append("")
    lines.append("=" * 62)
    lines.append("  Worker Stats")
    lines.append("-" * 62)
    lines.append(f"  {'worker':>8}  {'records':>10}  {'errors':>8}  {'rate':>12}  {'elapsed':>10}")
    lines.append("-" * 62)

    for r in results:
        recs = getattr(r, "records", 0)
        errs = getattr(r, "errors", 0)
        elapsed = getattr(r, "elapsed_seconds", 0.0)
        rate = recs / max(1e-9, elapsed)
        total_records += recs
        total_errors += errs
        if rate > max_rate:
            max_rate = rate
        lines.append(
            f"  {'w-' + str(getattr(r, 'worker_id', '?')):>8}"
            f"  {recs:>10,}"
            f"  {errs:>8,}"
            f"  {rate:>10,.0f}/s"
            f"  {elapsed:>9,.1f}s"
        )

    lines.append("-" * 62)
    overall_rate = total_records / max(1e-9, wall_seconds)
    lines.append(f"  {'TOTAL':>8}  {total_records:>10,}  {total_errors:>8,}  {overall_rate:>10,.0f}/s  {wall_seconds:>9,.1f}s")
    lines.append(f"  Peak worker rate: {max_rate:,.0f} rec/s")
    if len(results) > 1:
        rates = [getattr(r, "records", 0) / max(1e-9, getattr(r, "elapsed_seconds", 0.0)) for r in results]
        avg_rate = sum(rates) / len(rates)
        lines.append(f"  Avg  worker rate: {avg_rate:,.0f} rec/s")
    lines.append("=" * 62)
    lines.append("")
    return "\n".join(lines)
