from __future__ import annotations

import cProfile
from contextlib import contextmanager
from typing import Iterator

from chia._tests.util.misc import BenchmarkRunner
from chia.wallet.trading.offer import Offer

with_profile = False

# gprof2dot -f pstats offer-parsing.profile >p.dot && dot -Tpng p.dot >offer-parsing.png
# gprof2dot -f pstats offered-coins.profile >c.dot && dot -Tpng c.dot >offered-coins.png


@contextmanager
def enable_profiler(name: str) -> Iterator[None]:
    if not with_profile:
        yield
        return

    with cProfile.Profile() as pr:
        yield

    pr.create_stats()
    pr.dump_stats(f"{name}.profile")


def test_offer_parsing_performance(benchmark_runner: BenchmarkRunner) -> None:
    offer_bytes = bytes.fromhex(test_offer)
    with benchmark_runner.assert_runtime(seconds=2.15):
        with enable_profiler("offer-parsing"):
            for _ in range(100):
                o = Offer.from_bytes(offer_bytes)
                assert o is not None


def test_offered_coins_performance(benchmark_runner: BenchmarkRunner) -> None:
    offer_bytes = bytes.fromhex(test_offer)
    o = Offer.from_bytes(offer_bytes)
    with benchmark_runner.assert_runtime(seconds=2.5):
        with enable_profiler("offered-coins"):
            for _ in range(100):
                c = o.get_offered_coins()
                assert len(c.items()) > 0


test_offer = "[encoded data, 12892 characters]"  # noqa: E501
